Spring使用POI實現Excel匯入匯出
阿新 • • 發佈:2018-11-25
Apache POI 是建立和維護操作各種符合Office Open XML(OOXML)標準和微軟的OLE 2複合文件格式(OLE2)的Java API。用它可以使用Java讀取和建立,修改MS Excel檔案.而且,還可以使用Java讀取和建立MS Word和MSPowerPoint檔案。Apache POI 提供Java操作Excel解決方案(適用於Excel97-2008)。
簡單理解就是通過POI,java可以與office建立聯絡。
本次專案實踐基於SSM框架,簡單封裝了Excel批量匯入匯出功能,實現過程如下
1. maven匯入java包:
[html] view plain copy
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</
- <version>3.5-FINAL</version>
- </dependency>
2. 建立Excel實體--ExcelBean
[java] view plain copy
- /**
- *
- * @Description: 匯入匯出excel
- * @author haipeng
- * @date 2017年4月11日
- */
- public class ExcelBean implements java.io.Serializable {
- private String headTextName;//列頭(標題)名
- private String propertyName;//對應欄位名
- private Integer cols;//合併單元格數
- private XSSFCellStyle cellStyle;
- public ExcelBean(){
- }
- public ExcelBean(String headTextName, String propertyName){
- this.headTextName = headTextName;
- this.propertyName = propertyName;
- }
- public ExcelBean(String headTextName, String propertyName, Integer cols) {
- super();
- this.headTextName = headTextName;
- this.propertyName = propertyName;
- this.cols = cols;
- }
- public String getHeadTextName() {
- return headTextName;
- }
- public void setHeadTextName(String headTextName) {
- this.headTextName = headTextName;
- }
- public String getPropertyName() {
- return propertyName;
- }
- public void setPropertyName(String propertyName) {
- this.propertyName = propertyName;
- }
- public Integer getCols() {
- return cols;
- }
- public void setCols(Integer cols) {
- this.cols = cols;
- }
- public XSSFCellStyle getCellStyle() {
- return cellStyle;
- }
- public void setCellStyle(XSSFCellStyle cellStyle) {
- this.cellStyle = cellStyle;
- }
- }
3. 封裝Excel工具類--ExcelUtils
[java] view plain copy- public class ExcelUtils {
- private final static String excel2003L =".xls"; //2003- 版本的excel
- private final static String excel2007U =".xlsx"; //2007+ 版本的excel
- /*************************************檔案上傳****************************/
- public static List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
- List<List<Object>> list = null;
- //建立Excel工作薄
- Workbook work = getWorkbook(in,fileName);
- if(null == work){
- throw new Exception("建立Excel工作薄為空!");
- }
- Sheet sheet = null;
- Row row = null;
- Cell cell = null;
- list = new ArrayList<List<Object>>();
- //遍歷Excel中所有的sheet
- for (int i = 0; i < work.getNumberOfSheets(); i++) {
- sheet = work.getSheetAt(i);
- if(sheet==null){continue;}
- //遍歷當前sheet中的所有行
- for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {
- row = sheet.getRow(j);
- if(row==null||row.getFirstCellNum()==j){continue;}
- //遍歷所有的列
- List<Object> li = new ArrayList<Object>();
- for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
- cell = row.getCell(y);
- li.add(getCellValue(cell));
- }