[轉載]原文地址:https://blog.csdn.net/vbirdbest/article/details/72870714
一 :簡介
開發中經常會設計到excel的處理,如導出Excel,導入Excel到數據庫中,操作Excel目前有兩個框架,一個是apache 的poi, 另一個是 Java Excel
Apache POI 簡介是用Java編寫的免費開源的跨平台的 Java API,Apache POI提供API給Java程式對Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式檔案讀和寫的功能。POI為“Poor Obfuscation Implementation”的首字母縮寫,意為“可憐的模糊實現”。
官方主頁: http://poi.apache.org/index.html
API文檔: http://poi.apache.org/apidocs/index.html
Java Excel是一開放源碼項目,通過它Java開發人員可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件。jxl 由於其小巧 易用的特點, 逐漸已經取代了 POI-excel的地位, 成為了越來越多的java開發人員生成excel文件的首選。
由於apache poi 在項目中用的比較多,本篇博客只講解apache poi,不講jxl
二:Apache POI常用的類
HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能。
XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
HWPF - 提供讀寫Microsoft Word DOC97格式檔案的功能。
XWPF - 提供讀寫Microsoft Word DOC2003格式檔案的功能。
HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。
HDGF - 提供讀Microsoft Visio格式檔案的功能。
HPBF - 提供讀Microsoft Publisher格式檔案的功能。
HSMF - 提供讀Microsoft Outlook格式檔案的功能。
在開發中我們經常使用HSSF用來操作Excel處理表格數據,對於其它的不經常使用。
HSSF 是Horrible SpreadSheet Format的縮寫,通過HSSF,你可以用純Java代碼來讀取、寫入、修改Excel文件。HSSF 為讀取操作提供了兩類API:usermodel和eventusermodel,即“用戶模型”和“事件-用戶模型”。
常用的類和方法
HSSFWorkbook :工作簿,代表一個excel的整個文檔
HSSFWorkbook(); // 創建一個新的工作簿
HSSFWorkbook(InputStream inputStream); // 創建一個關聯輸入流的工作簿,可以將一個excel文件封裝成工作簿
HSSFSheet createSheet(String sheetname); 創建一個新的Sheet
HSSFSheet getSheet(String sheetName); 通過名稱獲取Sheet
HSSFSheet getSheetAt(int index); // 通過索引獲取Sheet,索引從0開始
HSSFCellStyle createCellStyle(); 創建單元格樣式
int getNumberOfSheets(); 獲取sheet的個數
setActiveSheet(int index); 設置默認選中的工作表
write();
write(File newFile);
write(OutputStream stream);
HSSFSheet:工作表
HSSFRow createRow(int rownum); 創建新行,需要指定行號,行號從0開始
HSSFRow getRow(int index); 根據索引獲取指定的行
int addMergedRegion(CellRangeAddress region); 合並單元格
CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol); 單元格范圍, 用於合並單元格,需要指定要合並的首行、最后一行、首列、最后一列。
autoSizeColumn(int column); 自動調整列的寬度來適應內容
getLastRowNum(); 獲取最后的行的索引,沒有行或者只有一行的時候返回0
setColumnWidth(int columnIndex, int width); 設置某一列的寬度,width=字符個數 * 256,例如20個字符的寬度就是20 * 256
HSSFRow :行
HSSFCell createCell(int column); 創建新的單元格
HSSFCell setCell(shot index);
HSSFCell getCell(shot index);
setRowStyle(HSSFCellStyle style); 設置行樣式
short getLastCellNum(); 獲取最后的單元格號,如果單元格有第一個開始算,lastCellNum就是列的個數
setHeightInPoints(float height); 設置行的高度
HSSFCell:單元格
setCellValue(String value); 設置單元格的值
setCellType(); 設置單元格類型,如 字符串、數字、布爾等
setCellStyle(); 設置單元格樣式
String getStringCellValue(); 獲取單元格中的字符串值
setCellStyle(HSSFCellStyle style); 設置單元格樣式,例如字體、加粗、格式化
setCellFormula(String formula); 設置計算公式,計算的結果作為單元格的值,也提供了異常常用的函數,如求和”sum(A1,C1)”、日期函數、字符串相關函數、CountIf和SumIf函數、隨機數函數等
HSSFCellStyle :單元格樣式
setFont(Font font); 為單元格設置字體樣式
setAlignment(HorizontalAlignment align); // 設置水平對齊方式
setVerticalAlignment(VerticalAlignment align); // 設置垂直對齊方式
setFillPattern(FillPatternType fp);
setFillForegroundColor(short bg); 設置前景色
setFillBackgroundColor(short bg); 設置背景顏色
HSSFFont:字體,
setColor(short color); // 設置字體顏色
setBold(boolean bold); // 設置是否粗體
setItalic(boolean italic); 設置傾斜
setUnderline(byte underline); 設置下划線
HSSFName:名稱
HSSFDataFormat :日期格式化
HSSFHeader : Sheet的頭部
HSSFFooter :Sheet的尾部
HSSFDateUtil :日期工具
HSSFPrintSetup :打印設置
HSSFErrorConstants:錯誤信息表
Excel中的工作簿、工作表、行、單元格中的關系:
一個Excel文件對應於一個workbook(HSSFWorkbook),
一個workbook可以有多個sheet(HSSFSheet)組成,
一個sheet是由多個row(HSSFRow)組成,
一個row是由多個cell(HSSFCell)組成
1
2
3
4
三:基礎示例
首先引入apache poi的依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
1
2
3
4
5
示例一:在桌面上生成一個Excel文件
public static void createExcel() throws IOException{
// 獲取桌面路徑
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
File file = new File(filePath);
OutputStream outputStream = new FileOutputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("id");
row.createCell(1).setCellValue("訂單號");
row.createCell(2).setCellValue("下單時間");
row.createCell(3).setCellValue("個數");
row.createCell(4).setCellValue("單價");
row.createCell(5).setCellValue("訂單金額");
row.setHeightInPoints(30); // 設置行的高度
HSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("NO00001");
// 日期格式化
HSSFCellStyle cellStyle2 = workbook.createCellStyle();
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
sheet.setColumnWidth(2, 20 * 256); // 設置列的寬度
HSSFCell cell2 = row1.createCell(2);
cell2.setCellStyle(cellStyle2);
cell2.setCellValue(new Date());
row1.createCell(3).setCellValue(2);
// 保留兩位小數
HSSFCellStyle cellStyle3 = workbook.createCellStyle();
cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
HSSFCell cell4 = row1.createCell(4);
cell4.setCellStyle(cellStyle3);
cell4.setCellValue(29.5);
// 貨幣格式化
HSSFCellStyle cellStyle4 = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setFontName("華文行楷");
font.setFontHeightInPoints((short)15);
font.setColor(HSSFColor.RED.index);
cellStyle4.setFont(font);
HSSFCell cell5 = row1.createCell(5);
cell5.setCellFormula("D2*E2"); // 設置計算公式
// 獲取計算公式的值
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
cell5 = e.evaluateInCell(cell5);
System.out.println(cell5.getNumericCellValue());
workbook.setActiveSheet(0);
workbook.write(outputStream);
outputStream.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
示例2:讀取Excel,解析數據
public static void readExcel() throws IOException{
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workbook.getSheet("Sheet1");
int lastRowIndex = sheet.getLastRowNum();
System.out.println(lastRowIndex);
for (int i = 0; i <= lastRowIndex; i++) {
HSSFRow row = sheet.getRow(i);
if (row == null) { break; }
short lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
String cellValue = row.getCell(j).getStringCellValue();
System.out.println(cellValue);
}
}
bufferedInputStream.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
四:Java Web 中導出和導入Excel
1、導出示例
@SuppressWarnings("resource")
@RequestMapping("/export")
public void exportExcel(HttpServletResponse response, HttpSession session, String name) throws Exception {
String[] tableHeaders = {"id", "姓名", "年齡"};
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Font font = workbook.createFont();
font.setColor(HSSFColor.RED.index);
font.setBold(true);
cellStyle.setFont(font);
// 將第一行的三個單元格給合並
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
HSSFRow row = sheet.createRow(0);
HSSFCell beginCell = row.createCell(0);
beginCell.setCellValue("通訊錄");
beginCell.setCellStyle(cellStyle);
row = sheet.createRow(1);
// 創建表頭
for (int i = 0; i < tableHeaders.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(tableHeaders[i]);
cell.setCellStyle(cellStyle);
}
List<User> users = new ArrayList<>();
users.add(new User(1L, "張三", 20));
users.add(new User(2L, "李四", 21));
users.add(new User(3L, "王五", 22));
for (int i = 0; i < users.size(); i++) {
row = sheet.createRow(i + 2);
User user = users.get(i);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getAge());
}
OutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=template.xls");
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
2、導入示例
1、使用SpringMVC上傳文件,需要用到commons-fileupload
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
1
2
3
4
5
2、需要在spring的配置文件中配置一下multipartResolver
<bean name="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
</bean>
1
2
3
4
3、index.jsp
<a href="/Spring-Mybatis-Druid/user/export">導出</a> <br/>
<form action="/Spring-Mybatis-Druid/user/import" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="導入Excel">
</form>
1
2
3
4
5
6
4、解析上傳的.xls文件
@SuppressWarnings("resource")
@RequestMapping("/import")
public void importExcel(@RequestParam("file") MultipartFile file) throws Exception{
InputStream inputStream = file.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
//HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
HSSFSheet sheet = workbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = 2; i <= lastRowNum; i++) {
HSSFRow row = sheet.getRow(i);
int id = (int) row.getCell(0).getNumericCellValue();
String name = row.getCell(1).getStringCellValue();
int age = (int) row.getCell(2).getNumericCellValue();
System.out.println(id + "-" + name + "-" + age);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
導出效果:
這里寫圖片描述
導入效果:
這里寫圖片描述
項目示例代碼下載地址:
http://download.csdn.net/detail/vbirdbest/9861536
五:相關文章:
http://www.cnblogs.com/Damon-Luo/p/5919656.html
http://www.cnblogs.com/LiZhiW/p/4313789.html