Excel轉Html

来源:http://www.cnblogs.com/androidshouce/archive/2016/07/13/5665614.html
-Advertisement-
Play Games

項目結構: 這是一個maven項目,主函數在Client類裡面 當運行程式的後,控制台情況: 當我們刷新了test.html文件後,用瀏覽器打開效果: 說一下這個過程的設計思路: 1.讀取excel文件 2.利用velocity模板工具把讀取的內容渲染到html裡面 整個過程就兩個步驟,是不是非常簡 ...


項目結構:

這是一個maven項目,主函數在Client類裡面

當運行程式的後,控制台情況:

當我們刷新了test.html文件後,用瀏覽器打開效果:

說一下這個過程的設計思路:

1.讀取excel文件

2.利用velocity模板工具把讀取的內容渲染到html裡面

整個過程就兩個步驟,是不是非常簡單。

當我們在把這兩個過程再細化一下,思路就更加清晰明瞭了。

1.1.怎樣讀取或者寫入Excel文件呢?

java的poi技術讀,寫Excel[2003-2007,2010]

2.1.怎樣使用velocity模板工具呢?

apache的開源項目-模板引擎(Velocity)_學習了兩天就上手啦_源碼下載

 

有了上面1.1和2.1的基礎,現在我們要做的工作,就是把他們串起來,就實現了Excel轉Html

為了自己以後一看源碼就知道怎樣做,我習慣貼源碼出來。 當然還會有源碼下載的(在文章末尾)。

 

===============================================

源碼部分:

===============================================

/excel2html/src/main/java/com/b510/excel/client/Client.java

複製代碼
 1 package com.b510.excel.client;
 2 
 3 import java.util.List;
 4 
 5 import com.b510.excel.common.Common;
 6 import com.b510.excel.reader.ReadExcel;
 7 import com.b510.excel.vo.Student;
 8 import com.b510.excel.writer.WriteHtml;
 9 
10 public class Client {
11 
12     public static void main(String[] args) throws Exception {
13         String excel2010 = Common.STUDENT_INFO_XLSX_PATH;
14         // read the 2010 excel
15         List<Student> list1 = new ReadExcel().readExcel(excel2010);
16         if (list1 != null && list1.size() > 0) {
17             for (Student student : list1) {
18                 System.out.println("No. : " + student.getNo() + ", name : " + student.getName() + ", age : " + student.getAge() + ", score : " + student.getScore());
19             }
20             System.out.println("begin to write into html file");
21             WriteHtml.write(list1);
22         }
23 
24     }
25 }
複製代碼

/excel2html/src/main/java/com/b510/excel/common/Common.java

複製代碼
 1 package com.b510.excel.common;
 2 
 3 public class Common {
 4 
 5     public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
 6 
 7     public static final String EMPTY = "";
 8     public static final String POINT = ".";
 9     public static final String STUDENT_INFO_XLSX_PATH = "/student_info" + POINT + OFFICE_EXCEL_2010_POSTFIX;
10     public static final String NOT_EXCEL_FILE = " : Not the Excel file!";
11     public static final String PROCESSING = "Processing...";
12     
13     public static final String HTML_FILE = "test.html";
14     public static final String TEST_HTML_FILE = "./test.html";
15 
16 }
複製代碼

/excel2html/src/main/java/com/b510/excel/reader/ReadExcel.java

複製代碼
  1 package com.b510.excel.reader;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import org.apache.poi.hssf.usermodel.HSSFCell;
  9 import org.apache.poi.hssf.usermodel.HSSFRow;
 10 import org.apache.poi.hssf.usermodel.HSSFSheet;
 11 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 12 import org.apache.poi.xssf.usermodel.XSSFCell;
 13 import org.apache.poi.xssf.usermodel.XSSFRow;
 14 import org.apache.poi.xssf.usermodel.XSSFSheet;
 15 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 16 
 17 import com.b510.excel.common.Common;
 18 import com.b510.excel.util.Util;
 19 import com.b510.excel.vo.Student;
 20 
 21 public class ReadExcel {
 22     
 23     /**
 24      * read the Excel file
 25      * @param path  the path of the Excel file
 26      * @return
 27      * @throws IOException
 28      */
 29     public List<Student> readExcel(String path) throws IOException {
 30         if (path == null || Common.EMPTY.equals(path)) {
 31             return null;
 32         } else {
 33             String postfix = Util.getPostfix(path);
 34             if (!Common.EMPTY.equals(postfix)) {
 35                 if (Common.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
 36                     return readXlsx(path);
 37                 }
 38             } else {
 39                 System.out.println(path + Common.NOT_EXCEL_FILE);
 40             }
 41         }
 42         return null;
 43     }
 44 
 45     /**
 46      * Read the Excel 2010
 47      * @param path the path of the excel file
 48      * @return
 49      * @throws IOException
 50      */
 51     @SuppressWarnings("resource")
 52     public List<Student> readXlsx(String path) throws IOException {
 53         System.out.println(Common.PROCESSING + path);
 54         InputStream is = this.getClass().getResourceAsStream(path);  
 55         XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
 56         Student student = null;
 57         List<Student> list = new ArrayList<Student>();
 58         // Read the Sheet
 59         for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
 60             XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
 61             if (xssfSheet == null) {
 62                 continue;
 63             }
 64             // Read the Row
 65             for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
 66                 XSSFRow xssfRow = xssfSheet.getRow(rowNum);
 67                 if (xssfRow != null) {
 68                     student = new Student();
 69                     XSSFCell no = xssfRow.getCell(0);
 70                     XSSFCell name = xssfRow.getCell(1);
 71                     XSSFCell age = xssfRow.getCell(2);
 72                     XSSFCell score = xssfRow.getCell(3);
 73                     student.setNo(getValue(no));
 74                     student.setName(getValue(name));
 75                     student.setAge(getValue(age));
 76                     student.setScore(Float.valueOf(getValue(score)));
 77                     list.add(student);
 78                 }
 79             }
 80         }
 81         return list;
 82     }
 83 
 84     /**
 85      * Read the Excel 2003-2007
 86      * @param path the path of the Excel
 87      * @return
 88      * @throws IOException
 89      */
 90     @SuppressWarnings("resource")
 91     public List<Student> readXls(String path) throws IOException {
 92         System.out.println(Common.PROCESSING + path);
 93         InputStream is = this.getClass().getResourceAsStream(path);  
 94         HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
 95         Student student = null;
 96         List<Student> list = new ArrayList<Student>();
 97         // Read the Sheet
 98         for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
 99             HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
100             if (hssfSheet == null) {
101                 continue;
102             }
103             // Read the Row
104             for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
105                 HSSFRow hssfRow = hssfSheet.getRow(rowNum);
106                 if (hssfRow != null) {
107                     student = new Student();
108                     HSSFCell no = hssfRow.getCell(0);
109                     HSSFCell name = hssfRow.getCell(1);
110                     HSSFCell age = hssfRow.getCell(2);
111                     HSSFCell score = hssfRow.getCell(3);
112                     student.setNo(getValue(no));
113                     student.setName(getValue(name));
114                     student.setAge(getValue(age));
115                     student.setScore(Float.valueOf(getValue(score)));
116                     list.add(student);
117                 }
118             }
119         }
120         return list;
121     }
122 
123     @SuppressWarnings("static-access")
124     private String getValue(XSSFCell xssfRow) {
125         if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
126             return String.valueOf(xssfRow.getBooleanCellValue());
127         } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
128             return String.valueOf(xssfRow.getNumericCellValue());
129         } else {
130             return String.valueOf(xssfRow.getStringCellValue());
131         }
132     }
133 
134     @SuppressWarnings("static-access")
135     private String getValue(HSSFCell hssfCell) {
136         if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
137             return String.valueOf(hssfCell.getBooleanCellValue());
138         } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
139             return String.valueOf(hssfCell.getNumericCellValue());
140         } else {
141             return String.valueOf(hssfCell.getStringCellValue());
142         }
143     }
144 }
複製代碼

/excel2html/src/main/java/com/b510/excel/util/Util.java

複製代碼
 1 package com.b510.excel.util;
 2 
 3 import com.b510.excel.common.Common;
 4 
 5 public class Util {
 6 
 7     /**
 8      * get postfix of the path
 9      * @param path
10      * @return
11      */
12     public static String getPostfix(String path) {
13         if (path == null || Common.EMPTY.equals(path.trim())) {
14             return Common.EMPTY;
15         }
16         if (path.contains(Common.POINT)) {
17             return path.substring(path.lastIndexOf(Common.POINT) + 1, path.length());
18         }
19         return Common.EMPTY;
20     }
21 }
複製代碼

/excel2html/src/main/java/com/b510/excel/vm/student.vm

複製代碼
 1 <!DOCTYPE html>
 2 <html>
 3 <title>HTML Tutorial</title>
 4 <style>
 5 table {
 6     width:100%;
 7 }
 8 table, th, td {
 9     border: 1px solid black;
10     border-collapse: collapse;
11 }
12 th, td {
13     padding: 5px;
14     text-align: left;
15 }
16 table#t01 tr:nth-child(even) {
17     background-color: #eee;
18 }
19 table#t01 tr:nth-child(odd) {
20    background-color:#fff;
21 }
22 table#t01 th    {
23     background-color: black;
24     color: white;
25 }
26 </style>
27 <body>
28 
29   <table id="t01">
30   <tr>
31     <th>S/N</th>
32     <th>ID</th>        
33     <th>Name</th>
34     <th>Age</th>
35     <th>Score</th>
36   </tr>
37 #set( $count = 1 )
38 #foreach( $student in $students)
39      <tr>
40         <td>$count</td>
41         <td>$student.no</td>    
42         <td>$student.name</td>    
43         <td>$student.age</td>    
44         <td>$student.score</td>    
45       </tr>
46     #set( $count = $count + 1 )
47 #end
48 </table>
49 </body>
50 </html>
複製代碼

/excel2html/src/main/java/com/b510/excel/vo/Student.java

複製代碼
 1 package com.b510.excel.vo;
 2 
 3 public class Student {
 4 
 5     private Integer id;
 6     private String no;
 7     private String name;
 8     private String age;
 9     private float score;
10 
11     public Integer getId() {
12         return id;
13     }
14 
15     public void setId(Integer id) {
16         this.id = id;
17     }
18 
19     public String getNo() {
20         return no;
21     }
22 
23     public void setNo(String no) {
24         this.no = no;
25     }
26 
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         this.name = name;
33     }
34 
35     public String getAge() {
36         return age;
37     }
38 
39     public void setAge(String age) {
40         this.age = age;
41     }
42 
43     public float getScore() {
44         return score;
45     }
46 
47     public void setScore(float score) {
48         this.score = score;
49     }
50 
51 }
複製代碼

/excel2html/src/main/java/com/b510/excel/writer/WriteHtml.java

複製代碼
 1 package com.b510.excel.writer;
 2 
 3 import java.io.File;
 4 import java.io.FileWriter;
 5 import java.io.StringWriter;
 6 import java.util.List;
 7 
 8 import org.apache.velocity.Template;
 9 import org.apache.velocity.VelocityContext;
10 import org.apache.velocity.app.VelocityEngine;
11 
12 import com.b510.excel.common.Common;
13 import com.b510.excel.vo.Student;
14 
15 public class WriteHtml {
16 
17     private static String createCode(String fileVMPath, List<Student> students) throws Exception {
18         VelocityEngine velocityEngine = new VelocityEngine();
19         velocityEngine.setProperty("input.encoding", "UTF-8");
20         velocityEngine.setProperty("output.encoding", "UTF-8");
21         velocityEngine.init();
22         Template template = velocityEngine.getTemplate(fileVMPath);
23         VelocityContext velocityContext = new VelocityContext();
24         velocityContext.put("students", students);
25         StringWriter stringWriter = new StringWriter();
26         template.merge(velocityContext, stringWriter);
27         return stringWriter.toString();
28     }
29 
30     public static void write(List<Student> students) throws Exception {
31         System.out.println("write begin");
32         File file = new File(Common.TEST_HTML_FILE);
33         FileWriter fw = new FileWriter(file);
34         fw.write(createCode("./src/main/java/com/b510/excel/vm/student.vm", students));
35         fw.flush();
36         fw.close();
37         System.out.println("write end. Refresh the project before seeing the excel2html/" + Common.HTML_FILE);
38     }
39 }
複製代碼

/excel2html/pom.xml

複製代碼
 1 <?xml version="1.0"?>
 2 <project
 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
 4     xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>hongten.exl2html</groupId>
 8     <artifactId>excel2html</artifactId>
 9     <version>0.0.1</version>
10 
11     <name>excel2html</name>
12     <url>http://maven.apache.org</url>
13 
14     <properties>
15         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16     </properties>
17 
18     <dependencies>
19         <dependency>
20             <groupId>junit</groupId>
21             <artifactId>junit</artifactId>
22             <version>3.8.1</version>
23             <scope>test</scope>
24         </dependency>
25 
26         <dependency>
27             <groupId>org.apache.poi</groupId>
28             <artifactId>poi</artifactId>
29             <version>3.12</version>
30         </dependency>
31 
32         <dependency>
33             <groupId>org.apache.poi</groupId>
34             <artifactId>poi-ooxml</artifactId>
35             <version>3.12</version>
36         </dependency>
37 
38         <dependency>
39             <groupId>org.apache.poi</groupId>
40             <artifactId>poi-ooxml-schemas</artifactId>
41             	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • JSmooth 0.9.9-7 在將 jar 文件打包成 exe 文件時報錯:jsmooth compilation failed error null 原因,沒有指定 logo 圖片文件。 http://kechengpuzi.com/q/s14902409 連接中說:還有可能是 logo 文件圖 ...
  • 利用雲視頻實現線上教育和美女主播系統。 最近美女主播跟游戲主播很火啊,哥也在整個美女視頻直播系統,相對其他web應用。視頻直播相對來說還是有點複雜。使用FMS搭建了服務端測試一下,直播還是不夠穩定。後來試了下阿裡雲視頻服務,感覺還可以,但是它沒有提供客戶端。然後找到了網易雲視頻,它有提供了客戶端,試 ...
  • 一、自定義攔截器 預設的攔截器能實現的功能是有限的,Struts2 支持自定義攔截器。 二、攔截器類 1.實現 Interceptor 介面 2.繼承 AbstractInterceptor 抽象類,需要實現 public String intercept(ActionInvocation acti ...
  • python 發郵件的功能 ...
  • c++中:的作用:初始化列表,後面的表達式用於初始化它的成員變數,或者基類的成員變數 。 c++中::的作用: 雙冒號 :: 操作符被稱為域操作符(scope operator),含義和用法如下:1.在類外部聲明成員函數。void Point::Area(){};2.調用全局函數;表示引用成員函數變 ...
  • ...
  • 創建FileUtil.php文件,內容及調用方式如下: <?php /** * 操縱文件類 * * 例子: * FileUtil::createDir('a/1/2/3'); 測試建立文件夾 建一個a/1/2/3文件夾 * FileUtil::createFile('b/1/2/3'); 測試建立文 ...
  • C++中的const關鍵字的用法非常靈活,而使用const將大大改善程式的健壯性,本人根據各方面查到的資料進行總結如下,期望對朋友們有所幫助。 Const 是C++中常用的類型修飾符,常類型是指使用類型修飾符const說明的類型,常類型的變數或對象的值是不能被更新的。 No. 作用 說明 參考代碼 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...