javascript
【SpringBoot】SpringBoot 操作 Excel 完整示例(含源码GitHub)
參考博客:博客園 - Spring Boot 操作 Excel
示例GitHub:spring-boot-study/spring-boot-study-excel/
1、新建 Spring Boot Maven 示例工程項目
注意:本示例是用 IDEA 開發(fā)工具
File > New > Project,如下圖選擇 Spring Initializr 然后點擊 【Next】下一步
填寫 GroupId(包名)、Artifact(項目名) 即可。點擊 下一步
groupId=com.fishpro
artifactId=excel
選擇依賴 Spring Web Starter 前面打鉤。
項目名設置為 spring-boot-study-excel.
文件上傳不需要引入第三方組件。
2、依賴引入 Pom.xml
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>3、操作 Excel
不同的 Excel 版本具有不同的類來操作本示例中使用 xls 后綴版本。詳細請參見 poi - 官方文檔
3.1 創(chuàng)建 Workbook
HSSFWorkbook 是操作 Excel2003 以前(包括2003)的版本,擴展名是.xls;
XSSFWorkbook 是操作 Excel2007 后的版本,擴展名是.xlsx;
SXSSFWorkbook 是操作 Excel2007 后的版本,擴展名是.xlsx;
3.2 創(chuàng)建工作表 Sheet
工作表名稱不要超過 31 個字符
名稱不能含有特殊字符
可以使用 WorkbookUtil.createSafeSheetName 來創(chuàng)建安全的工作表名稱
3.3 創(chuàng)建單元格 Cells
先有行在有列,先要創(chuàng)建 Row 在創(chuàng)建 Cell
- 創(chuàng)建一個樣式
- 創(chuàng)建一個日期類型的值
- 創(chuàng)建日期、小數(shù)、字符 、布爾等類型
- 創(chuàng)建一個邊框類型單元格
- 數(shù)據格式化單元格
3.4 讀取與獲取Excel
使用 File 的方式讀取 Excel
public static void OpenExcelByFile(){ try {Workbook wb = WorkbookFactory.create(new File("workbook.xls"));//讀取Sheet sheet=wb.getSheetAt(0);//第一個Sheet sheet1=wb.getSheet("sheet1");//根據名稱讀取Row row=sheet.getRow(0);//獲取行Cell cell=row.getCell(0);//獲取第一行}catch (Exception ex){// do something} }使用 FileInputStream 需要內存支持
public static void OpenExcelByFileInputStream(){try {Workbook wb = WorkbookFactory.create(new FileInputStream("workbook.xls"));//遍歷}catch (Exception ex){// do something} }4、使用示例
使用方式:運行ExcelApplicationTests.java即可生成excel文件,效果如下圖
4.1 項目結構
因為和另外一個項目合并了,所以只看黃色框中的文件即可
4.2 源碼
ExcelUtil.java
package cn.hanquan.excel.util;import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.WorkbookUtil; import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.*; import java.util.Calendar; import java.util.Date;public class ExcelUtil {public static void main(String [] args){}/*** ## 3.1 創(chuàng)建 Workbook* - `HSSFWorkbook` 是操作 Excel2003 以前(包括2003)的版本,擴展名是.xls;* - `XSSFWorkbook` 是操作 Excel2007 后的版本,擴展名是.xlsx;* - `SXSSFWorkbook` 是操作 Excel2007 后的版本,擴展名是.xlsx;** 返回空 輸出 workbook.xls workbook.xlsx 注意此時 excel元素不全,還不能打開*/public static void CreateNewWorkbook() {Workbook wb = new HSSFWorkbook();try {System.out.println("創(chuàng)建workbook.xls");OutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);} catch (Exception e) {e.printStackTrace();}Workbook wb2 = new XSSFWorkbook();try (OutputStream fileOut = new FileOutputStream("workbook.xlsx")) {wb2.write(fileOut);} catch (Exception e) {System.out.println("創(chuàng)建workbook.xlsx");e.printStackTrace();}}/***## 3.2 創(chuàng)建工作表 Sheet* - 工作表名稱不要超過 31 個字符* - 名稱不能含有特殊字符* - 可以使用 WorkbookUtil.createSafeSheetName 來創(chuàng)建安全的工作表名稱* 返回空 輸出 workbook.xls 注意此時 excel元素不全,還不能打開* */public static void CreateNewSheet() {Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();Sheet sheet1 = wb.createSheet("new sheet");Sheet sheet2 = wb.createSheet("new second sheet");String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]"); // returns " O'Brien's sales "Sheet sheet3 = wb.createSheet(safeName);try {System.out.println("創(chuàng)建工作表");OutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);System.out.println("創(chuàng)建工作表成功");} catch (Exception e) {System.out.println("創(chuàng)建工作表失敗");e.printStackTrace();}}/***## 3.3 創(chuàng)建單元格 Cells* - 先有行在有列,先要創(chuàng)建 Row 在創(chuàng)建 Cell* - 創(chuàng)建一個樣式* - 創(chuàng)建一個日期類型的值* - 創(chuàng)建日期、小數(shù)、字符 、布爾等類型* - 創(chuàng)建一個邊框類型單元格* - 數(shù)據格式化單元格* -* */public static void CreateNewCell() {Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();Sheet sheet = wb.createSheet("new sheet");//先行后列:先創(chuàng)建i行Row row_0 = sheet.createRow(0);Row row_1 = sheet.createRow(1);Row row_2 = sheet.createRow(2);Row row_3 = sheet.createRow(3);Row row_4 = sheet.createRow(4);Row row_5 = sheet.createRow(5);Row row_6 = sheet.createRow(6);//第0行第i列:標題row_0.createCell(0).setCellValue("編號");row_0.createCell(1).setCellValue("姓名");row_0.createCell(2).setCellValue("愛好");//創(chuàng)建列//創(chuàng)建不同的類型的單元格row_1.createCell(0).setCellValue(219);row_1.createCell(1).setCellValue("張三");row_1.createCell(2).setCellValue("敲代碼");row_2.createCell(0).setCellValue(220);row_2.createCell(1).setCellValue("李四");row_2.createCell(2).setCellValue("看代碼");row_3.createCell(0).setCellValue(221);row_3.createCell(1).setCellValue("李四");row_3.createCell(2).setCellValue("抄代碼");row_4.createCell(0).setCellValue(222);row_4.createCell(1).setCellValue("王五");row_4.createCell(2).setCellValue("配環(huán)境");row_5.createCell(0).setCellValue(223);row_5.createCell(1).setCellValue("趙六");row_5.createCell(2).setCellValue("吃東西");row_6.createCell(0).setCellValue(224);row_6.createCell(1).setCellValue("小七");Cell specialCell = row_6.createCell(2);specialCell.setCellValue("寫博客");// 邊框CellStyle style = wb.createCellStyle();style.setBorderBottom(BorderStyle.MEDIUM_DASHED);//底部邊框style.setBottomBorderColor(IndexedColors.BLACK.getIndex());style.setBorderLeft(BorderStyle.MEDIUM_DASHED);//左邊style.setLeftBorderColor(IndexedColors.GREEN.getIndex());style.setBorderRight(BorderStyle.MEDIUM_DASHED);//右邊style.setRightBorderColor(IndexedColors.BLUE.getIndex());style.setBorderTop(BorderStyle.MEDIUM_DASHED);//上邊style.setTopBorderColor(IndexedColors.BLUE.getIndex());//顏色specialCell.setCellStyle(style);try {OutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);} catch (Exception e) {e.printStackTrace();}finally {// 關閉流try {wb.close();} catch (IOException e) {e.printStackTrace();}}}/*** 使用 File 的方式讀取 Excel* 讀取單元格* */public static void OpenExcelByFile(){Workbook wb=null;try {System.out.println("使用 File 的方式讀取 Excel");wb = WorkbookFactory.create(new File("workbook.xls"));//讀取Sheet sheet = wb.getSheetAt(0);//第一個Sheet sheet1 = wb.getSheet("sheet1");//根據名稱讀取Row row = sheet.getRow(0);//獲取行Cell cell = row.getCell(0);//獲取第一行System.out.println("In OpenExcelByFile, cell = " + cell);} catch (Exception ex) {ex.printStackTrace();}finally {// 關閉流try {wb.close();} catch (IOException e) {e.printStackTrace();}}}/*** 使用 FileInputStream* */public static void OpenExcelByFileInputStream(){Workbook wb=null;try {System.out.println("使用 FileInputStream 的方式讀取 Excel");wb = WorkbookFactory.create(new FileInputStream("workbook.xls"));//讀取Sheet sheet = wb.getSheetAt(0);//第一個Sheet sheet1 = wb.getSheet("sheet1");//根據名稱讀取Row row = sheet.getRow(0);//獲取行Cell cell = row.getCell(1);System.out.println("In OpenExcelByFile, OpenExcelByFileInputStream = " + cell);}catch (Exception ex){ex.printStackTrace();}finally {// 關閉流try {wb.close();} catch (IOException e) {e.printStackTrace();}}} }ExcelApplication.java
package cn.hanquan.excel;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class ExcelApplication {public static void main(String[] args) {SpringApplication.run(ExcelApplication.class, args);} }ExcelApplicationTests.java
package cn.hanquan.excel;import cn.hanquan.excel.util.ExcelUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class) @SpringBootTest public class ExcelApplicationTests {@Testpublic void contextLoads() {}@Testpublic void TestCreateWorkbook(){ExcelUtil.CreateNewWorkbook();}@Testpublic void TestCreateSheet(){ExcelUtil.CreateNewSheet();}@Testpublic void TestCreateCell(){ExcelUtil.CreateNewCell();}@Testpublic void OpenAndReadExcel(){ExcelUtil.OpenExcelByFile();ExcelUtil.OpenExcelByFileInputStream();}/*** 應該串行執(zhí)行吧,不能直接跑全部,順序會亂* 所以寫了這個*/@Testpublic void TestAllInOrder(){ExcelUtil.CreateNewWorkbook();ExcelUtil.CreateNewSheet();ExcelUtil.CreateNewCell();ExcelUtil.OpenExcelByFile();ExcelUtil.OpenExcelByFileInputStream();} }總結
以上是生活随笔為你收集整理的【SpringBoot】SpringBoot 操作 Excel 完整示例(含源码GitHub)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Git】从Git远程存储库中删除所有.
- 下一篇: 【GitHub】GitHub 的 Pul