java的poi技術寫Excel的Sheet

来源:http://www.cnblogs.com/hongten/archive/2016/07/02/poi_sheet.html
-Advertisement-
Play Games

在這之前寫過關於java讀,寫Excel的blog如下: Excel轉Html java的poi技術讀,寫Excel[2003-2007,2010] java的poi技術讀取Excel[2003-2007,2010] java的poi技術讀取Excel數據到MySQL java的jxl技術導入Exc ...


在這之前寫過關於java讀,寫Excel的blog如下:

Excel轉Html

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

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

java的poi技術讀取Excel數據到MySQL

java的jxl技術導入Excel

java的poi技術讀取和導入Excel

 

然而,這篇blog主要內容是關於Excel裡面怎樣去寫Sheet數據。

那麼在Excel裡面什麼叫做Sheet呢?如下圖紅色框裡面的內容就是Excel的Sheet了。

我們需要知道怎樣創建一個Sheet,下麵是一個Sample:

 1 Workbook wb = new HSSFWorkbook();  // or new XSSFWorkbook();
 2 Sheet sheet1 = wb.createSheet("new sheet");
 3 Sheet sheet2 = wb.createSheet("second sheet");
 4 
 5 
 6 // You can use org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}
 7 // for a safe way to create valid names, this utility replaces invalid characters with a space (' ')
 8 String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]"); // returns " O'Brien's sales   "
 9 Sheet sheet3 = wb.createSheet(safeName);
10 
11 FileOutputStream fileOut = new FileOutputStream("workbook.xls");
12 wb.write(fileOut);
13 fileOut.close();

看了以後,會不會覺得So easy!這是因為Apache的poi給我們封裝了很多方法,提供了很好的介面。

下麵是我做的一個Demo,這個Demo的數據流如下:

MySQL資料庫 -- > Demo 程式 -- > Excel 文件

我們的Demo程式會從MySQL資料庫中讀取數據,然後把數據寫入到Excel文件中。

項目結構:

註意:紅色框裡面的jar包,你在下載源碼後,這些jar包不會存放到源碼裡面,需要手動下載!

在MySQL資料庫中,我們會用到兩張表: t_school, t_student.

 1 -- Table "t_school" DDL
 2 
 3 CREATE TABLE `t_school` (
 4   `no` int(16) NOT NULL AUTO_INCREMENT,
 5   `name` varchar(50) COLLATE utf8_bin NOT NULL,
 6   `desc` varchar(500) COLLATE utf8_bin DEFAULT NULL,
 7   `ranking` int(3) DEFAULT NULL,
 8   `address` varchar(200) COLLATE utf8_bin DEFAULT NULL,
 9   PRIMARY KEY (`no`)
10 ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
11 
12 -- Table "t_student" DDL
13 
14 CREATE TABLE `t_student` (
15   `student_no` int(16) NOT NULL AUTO_INCREMENT,
16   `school_no` int(16) NOT NULL,
17   `name` varchar(100) COLLATE utf8_bin DEFAULT NULL,
18   `address` varchar(200) COLLATE utf8_bin DEFAULT NULL,
19   `birthdate` varchar(15) COLLATE utf8_bin DEFAULT NULL,
20   `phone` varchar(15) COLLATE utf8_bin DEFAULT NULL,
21   PRIMARY KEY (`student_no`,`school_no`),
22   KEY `school_no` (`school_no`),
23   CONSTRAINT `school_no` FOREIGN KEY (`school_no`) REFERENCES `t_school` (`no`)
24 ) ENGINE=InnoDB AUTO_INCREMENT=100000023 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

在Excel文件中,我們要做的是在'School Summary' Sheet裡面寫入School的信息,而對於其他的Sheet,我們會把Shool的名稱命名為Sheet的Name,然後在每一個Sheet裡面寫入在這個Shool裡面的Student的信息。

兩張表裡面數據,大家可以通過blog末尾的下載鏈接獲得。

---------------------------------------------

                    代碼部分

---------------------------------------------

/ExcelHandler/src/com/b510/hongten/client/Client.java

 1 package com.b510.hongten.client;
 2 
 3 import java.util.List;
 4 
 5 import com.b510.hongten.db.SchoolDAO;
 6 import com.b510.hongten.excel.WriteExcel;
 7 import com.b510.hongten.vo.School;
 8 
 9 /**
10  * @author hongten
11  * @created Jun 16, 2016
12  */
13 public class Client {
14 
15     public static void main(String[] args) {
16         List<School> schools = SchoolDAO.getSchools();
17         WriteExcel writeExcel = new WriteExcel();
18         writeExcel.writeExcel(schools);
19     }
20 
21 }

/ExcelHandler/src/com/b510/hongten/common/Common.java

 1 package com.b510.hongten.common;
 2 
 3 /**
 4  * @author hongten
 5  * @created Jun 16, 2016
 6  */
 7 public class Common {
 8 
 9     // MySQL database connection configuration, you could write in *.properties
10     // file as also. For this demo, we write this configuration in this class
11     // file. By the way, I don't recommend this way ^_^.
12     public static String URL = "jdbc:mysql://localhost:3306/school";
13     public static String USER_NAME = "root";
14     public static String PASSWORD = "password1";
15     
16     public static String TARGET_FILE_PATH = "lib/excel_resources/school.xls";
17 
18     public static String SUMMARY = "Shool Summary";
19     public static String[] TITLES = { "S/N", "Name", "Description", "Ranking", "Address" };
20     public static String[] STUDENT_TITLE = { "S/N", "Name", "Birth Date", "Phone", "Address" };
21 }

/ExcelHandler/src/com/b510/hongten/db/ConnectionUtil.java

 1 package com.b510.hongten.db;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.SQLException;
 6 
 7 import org.apache.log4j.Logger;
 8 
 9 import com.b510.hongten.common.Common;
10 
11 /**
12  * @author hongten
13  * @created Jun 16, 2016
14  */
15 public class ConnectionUtil {
16 
17     static Logger logger = Logger.getLogger(ConnectionUtil.class);
18 
19     public static Connection getConn() {
20         logger.debug("-------- MySQL JDBC Connection Testing ------------");
21 
22         Connection connection = null;
23         try {
24             Class.forName("com.mysql.jdbc.Driver");
25         } catch (ClassNotFoundException e) {
26             logger.error("Where is your MySQL JDBC Driver?");
27             e.printStackTrace();
28         }
29 
30         logger.info("MySQL JDBC Driver Registered!");
31 
32         try {
33             connection = DriverManager.getConnection(Common.URL, Common.USER_NAME, Common.PASSWORD);
34             if(connection != null){
35                 logger.info("connecte successfully!");
36             }
37         } catch (SQLException e) {
38             logger.error("Connection Failed! Check output console");
39             e.printStackTrace();
40         }
41         return connection;
42 
43     }
44 
45     public static void closeConn(Connection conn) {
46         if (conn != null) {
47             try {
48                 logger.info("closing connection begin!");
49                 conn.close();
50                 logger.info("closing connection end!");
51             } catch (SQLException e) {
52                 e.printStackTrace();
53             }
54         } else {
55             logger.info("connection is not null!");
56         }
57     }
58 }

/ExcelHandler/src/com/b510/hongten/db/SchoolDAO.java

 1 package com.b510.hongten.db;
 2 
 3 import java.sql.Connection;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 
 9 import org.apache.log4j.Logger;
10 
11 import com.b510.hongten.vo.School;
12 import com.b510.hongten.vo.Student;
13 import com.mysql.jdbc.PreparedStatement;
14 
15 /**
16  * @author hongten
17  * @created Jun 16, 2016
18  */
19 public class SchoolDAO {
20 
21     static Logger logger = Logger.getLogger(SchoolDAO.class);
22 
23     public static List<School> getSchools() {
24         Connection conn = null;
25         PreparedStatement preparedStatement = null, preStat = null;
26         ResultSet rs = null, rs_student = null;
27         List<School> schools = new ArrayList<School>();
28 
29         try {
30             conn = ConnectionUtil.getConn();
31             String sql = "select * from t_school order by no";
32             preparedStatement = (PreparedStatement) conn.prepareStatement(sql);
33             rs = preparedStatement.executeQuery();
34             while (rs.next()) {
35                 int school_no = rs.getInt(1);
36                 if (school_no > 0) {
37                     School school = new School();
38                     school.setNo(school_no);
39                     school.setName(rs.getString("name"));
40                     school.setAddrss(rs.getString("address"));
41                     school.setDesc(rs.getString("desc"));
42                     school.setRanking(rs.getString("ranking"));
43 
44                     String studentSQL = "select * from t_student where school_no = ? ";
45                     preStat = (PreparedStatement) conn.prepareStatement(studentSQL);
46                     preStat.setInt(1, school_no);
47                     rs_student = preStat.executeQuery();
48                     List<Student> students = new ArrayList<>();
49                     while (rs_student.next()) {
50                         Student student = new Student();
51                         int std_no = rs_student.getInt(1);
52                         student.setStudentNo(std_no);
53                         student.setName(rs_student.getString("name"));
54                         student.setBirthdate(rs_student.getString("birthdate"));
55                         student.setPhone(rs_student.getString("phone"));
56                         student.setAddress(rs.getString("address"));
57                         students.add(student);
58                     }
59                     school.setStudents(students);
60                     schools.add(school);
61                 }
62             }
63         } catch (SQLException e) {
64             e.printStackTrace();
65             logger.error(e.getMessage());
66         } finally {
67             if (rs != null) {
68                 try {
69                     rs.close();
70                 } catch (SQLException e) {
71                     e.printStackTrace();
72                 }
73             }
74             if (preparedStatement != null) {
75                 try {
76                     preparedStatement.close();
77                 } catch (SQLException e) {
78                     e.printStackTrace();
79                 }
80             }
81             ConnectionUtil.closeConn(conn);
82         }
83         return schools;
84     }
85 }

/ExcelHandler/src/com/b510/hongten/excel/WriteExcel.java

  1 package com.b510.hongten.excel;
  2 
  3 import java.io.FileNotFoundException;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.util.List;
  7 
  8 import org.apache.log4j.Logger;
  9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 10 import org.apache.poi.ss.usermodel.Cell;
 11 import org.apache.poi.ss.usermodel.Row;
 12 import org.apache.poi.ss.usermodel.Sheet;
 13 import org.apache.poi.ss.usermodel.Workbook;
 14 
 15 import com.b510.hongten.common.Common;
 16 import com.b510.hongten.vo.School;
 17 import com.b510.hongten.vo.Student;
 18 
 19 /**
 20  * @author hongten
 21  * @created Jun 13, 2016
 22  */
 23 public class WriteExcel {
 24 
 25     static Logger logger = Logger.getLogger(WriteExcel.class);
 26 
 27     public void writeExcel(List<School> schools) {
 28         if (schools == null || schools.size() == 0) {
 29             return;
 30         }
 31         FileOutputStream fileOut = null;
 32         Workbook wb = new HSSFWorkbook();
 33         Sheet shool_sheet = wb.createSheet(Common.SUMMARY);
 34         shool_sheet.setAutobreaks(true);
 35         // Create a row and put some cells in it. Rows are 0 based.
 36         Row row = shool_sheet.createRow(0);
 37         String[] titles = Common.TITLES;
 38         int num = 0;
 39         for (String title : titles) {
 40             // Create a cell
 41             Cell cell = row.createCell(num++);
 42             cell.setCellValue(title);
 43         }
 44         int rowNum = 1;
 45         for (School school : schools) {
 46             row = shool_sheet.createRow(rowNum++);
 47             Cell cell = row.createCell(0);
 48             cell.setCellValue(school.getNo());
 49             cell = row.createCell(1);
 50             cell.setCellValue(school.getName());
 51             cell = row.createCell(2);
 52             cell.setCellValue(school.getDesc());
 53             cell = row.createCell(3);
 54             cell.setCellValue(school.getRanking());
 55             cell = row.createCell(4);
 56             cell.setCellValue(school.getAddrss());
 57 
 58             List<Student> students = school.getStudents();
 59             if (students != null && students.size() > 0) {
 60                 Sheet student_sheet = wb.createSheet(school.getName());
 61                 student_sheet.setAutobreaks(true);
 62                 // Create a row and put some cells in it. Rows are 0 based.
 63                 Row student_row = student_sheet.createRow(0);
 64                 String[] student_titles = Common.STUDENT_TITLE;
 65                 num = 0;
 66                 for (String title : student_titles) {
 67                     // Create a cell
 68                     Cell student_cell = student_row.createCell(num++);
 69                     student_cell.setCellValue(title);
 70                 }
 71                 int stuRowNum = 1;
 72                 for (Student student : students) {
 73                     student_row = student_sheet.createRow(stuRowNum++);
 74                     Cell student_cell = student_row.createCell(0);
 75                     student_cell.setCellValue(student.getStudentNo());
 76                     student_cell = student_row.createCell(1);
 77                     student_cell.setCellValue(student.getName());
 78                     student_cell = student_row.createCell(2);
 79                     student_cell.setCellValue(student.getBirthdate());
 80                     student_cell = student_row.createCell(3);
 81                     student_cell.setCellValue(student.getPhone());
 82                     student_cell = student_row.createCell(4);
 83                     student_cell.setCellValue(student.getAddress());
 84                 }
 85             }
 86         }
 87 
 88         try {
 89             fileOut = new FileOutputStream(Common.TARGET_FILE_PATH);
 90         } catch (FileNotFoundException e) {
 91             e.printStackTrace();
 92         }
 93         try {
 94             wb.write(fileOut);
 95         } catch (IOException e1) {
 96             e1.printStackTrace();
 97         }
 98         try {
 99             fileOut.close();
100         } catch (IOException e) {
101             e.printStackTrace();
102         }
103         logger.info("done");
104     }
105 
106 }

/ExcelHandler/src/com/b510/hongten/vo/School.java

 1 package com.b510.hongten.vo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 /**
 7  * @author hongten
 8  * @created Jun 16, 2016
 9  */
10 public class School {
11 
12     private int no;
13     private String name;
14     private String desc;
15     private String ranking;
16     private String addrss;
17 
18     private List<Student> students = new ArrayList<Student>();
19 
20     public int getNo() {
21         return no;
22     }
23 
24     public void setNo(int no) {
25         this.no = no;
26     }
27 
28     public String getName() {
29         return name;
30     }
31 
32     public void setName(String name) {
33         this.name = name;
34     }
35 
36     public String getDesc() {
37         return desc;
38     }
39 
40     public void setDesc(String desc) {
41         this.desc = desc;
42     }
43 
44     public String getRanking() {
45         return ranking;
46     }
47 
48     public void setRanking(String ranking) {
49         this.ranking = ranking;
50     }
51 
52     public String getAddrss() {
53         return addrss;
54     }
55 
56     public void setAddrss(String addrss) {
57         this.addrss = addrss;
58     }
59 
60     public List<Student> getStudents() {
61         return students;
62     }
63 
64     public void setStudents(List<Student> students) {
65         this.students = students;
66     }
67 
68 }

/ExcelHandler/src/com/b510/hongten/vo/Student.java

 1 package com.b510.hongten.vo;
 2 
 3 /**
 4  * @author hongten
 5  * @created Jun 16, 2016
 6  */
 7 public class Student {
 8 
 9     private int studentNo;
10     private String name;
11     private String address;
12     private String birthdate;
13     private String note;
14     private String phone;
15 
16     public int getStudentNo() {
17         return studentNo;
18     }
19 
20     public void setStudentNo(int studentNo) {
21         this.studentNo = studentNo;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31 
32     public String getAddress() {
33         return address;
34     }
35 
36     public void setAddress(String address) {
37         this.address = address;
38     }
39 
40     public String getBirthdate() {
41         return birthdate;
42     }
43 
44     public void setBirthdate(String birthdate) {
45         this.birthdate = birthdate;
46     }
47 
48     public String getNote() {
49         return note;
50     }
51 
52     public void setNote(String note) {
53         this.note = note;
54     }
55 
56     public String getPhone() {
57         return phone;
58     }
59 
60     public void setPhone(String phone) {
61         this.phone = phone;
62     }
63 
64 }

/ExcelHandler/src/log4j.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 3 <log4j:configuration debug="true"
 4     xmlns:log4j='http://jakarta.apache.org/log4j/'>
 5 
 6     <appender name="console" class="org.apache.log4j.ConsoleAppender">
 7         <layout class="org.apache.log4j.PatternLayout">
 8         <param name="ConversionPattern" 
 9           value
              
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 創建上下文對象:WordBoradEntities db = new WordBoradEntities(); 添加://1.1創建實體對象 User uObj = new User() { uName = "劉德華", uLoginName = "aaa", uPwd = "asdfasdfasd ...
  • 還是先上效果圖: 看完了上一篇UWP Composition API - GroupListView(一)的童鞋會問,這不是跟上一篇一樣的嗎??? 騙點擊的?? No,No,其實相對上一個有更簡單粗暴的方案,因為上篇是為了研究Composition API,所以含著淚都要做完(有沒有被騙的趕腳)。。 ...
  • 最終我決定通過webbrowser模擬登陸支付寶,獲取數據。根據業務需求,我需要把獲取支付寶的數據做成介面,供業務去調用。難點在於如何可以穩定的切換賬號,並且保證服務24小時可用。需要處理一系列的異常和超時。缺點是這邊變成單線程,登錄獲取數據只能一個進行完了再進行下一個。 簡單列下登錄流程 爬蟲服務 ...
  • ...
  • 題目:統計一個數字在排序數組中出現的次數。例如,輸入排序數組{1,2,3,3,3,3,4,5}和數字3,由於3在這個數組中出現了4次,因此輸出4. 思路1:該解法是最直觀的解法,可以先使用二分查找先找到這個元素,然後分別向左和向右遍歷,把左右相同的元素的個數都計算出來。 思路2:使用二分查找的拓展, ...
  • 轉載自http://www.infoq.com/cn/articles/netty-high-performance 1. 背景 1.1. 驚人的性能數據 最近一個圈內朋友通過私信告訴我,通過使用Netty4 + Thrift壓縮二進位編解碼技術,他們實現了10W TPS(1K的複雜POJO對象)的... ...
  • 懶人記錄 Hadoop2.7.1 集群搭建過程 2016-07-02 13:15:45 總結 除了配置hosts ,和免密碼互連之外,先在一臺機器上裝好所有東西 配置好之後,拷貝虛擬機,配置hosts和免密碼互連 之前在公司裝的時候jdk用的32位,hadoop的native包不能正常載入,浪費好多 ...
  • 開頭話: 網站,說實話,是第一次做,也就直接選擇了ThinkPHP這個開源框架。選擇這個框架的原因。。。已經不記得了 貌似在我當時的認知中只有這個了,其它更優秀的框架也是這個畢業設計做到後期再去瞭解的。想起來了,是覺得相對 於使用java開發web,感覺php的直接可解析性更加方便於開發,能讓我節省 ...
一周排行
    -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.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...