<dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> </dependencies>
import java.io.*; import java.util.*; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtil { public static List<List<String>> readExcel(String filePath) { List<List<String>> dataLst = null; InputStream is = null; try { //驗證文件是否合法 if (!validateExcel(filePath)) { return null; } // 判斷文件的類型,是2003還是2007 boolean isExcel2003 = true; if (isExcel2007(filePath)) { isExcel2003 = false; } // 調用本類提供的根據流讀取的方法 File file = new File(filePath); is = new FileInputStream(file); dataLst = read(is, isExcel2003); } catch (Exception ex) { ex.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { is = null; e.printStackTrace(); } } } return dataLst; } private static List<List<String>> read(InputStream inputStream, boolean isExcel2003) { List<List<String>> dataLst = null; try { //根據版本選擇創建Workbook的方式 Workbook wb = null; if (isExcel2003) { wb = new HSSFWorkbook(inputStream); } else { wb = new XSSFWorkbook(inputStream); } dataLst = read(wb); } catch (IOException e) { e.printStackTrace(); } return dataLst; } private static List<List<String>> read(Workbook wb) { int totalRows = 0; int totalCells = 0; List<List<String>> dataLst = new ArrayList<List<String>>(); // 得到第一個shell Sheet sheet = wb.getSheetAt(0); // 得到Excel的行數 totalRows = sheet.getPhysicalNumberOfRows(); // 得到Excel的列數 if (totalRows >= 1 && sheet.getRow(0) != null) { totalCells = sheet.getRow(0).getPhysicalNumberOfCells(); } //遍歷行 for (int r = 0; r < totalRows; r++) { Row row = sheet.getRow(r); if (row == null) { continue; } List<String> rowLst = new ArrayList<String>(); //遍歷列 for (int c = 0; c < totalCells; c++) { Cell cell = row.getCell(c); String cellValue = ""; if (null != cell) { // 以下是判斷數據的類型 switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: // 數字 cellValue = cell.getNumericCellValue() + ""; break; case HSSFCell.CELL_TYPE_STRING: // 字符串 cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean cellValue = cell.getBooleanCellValue() + ""; break; case HSSFCell.CELL_TYPE_FORMULA: // 公式 cellValue = cell.getCellFormula() + ""; break; case HSSFCell.CELL_TYPE_BLANK: // 空值 cellValue = ""; break; case HSSFCell.CELL_TYPE_ERROR: // 故障 cellValue = "非法字符"; break; default: cellValue = "未知類型"; break; } } rowLst.add(cellValue); } // 保存第r行的第c列 dataLst.add(rowLst); } return dataLst; } private static boolean validateExcel(String filePath) { // 檢查文件名是否為空或者是否是Excel格式的文件 if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) { return false; } // 檢查文件是否存在 File file = new File(filePath); if (file == null || !file.exists()) { return false; } return true; } private static boolean isExcel2003(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } private static boolean isExcel2007(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } public static void writeExcel(List<List<String>> dataList, String finalXlsxPath){ OutputStream out = null; try { // 讀取Excel文檔 File finalXlsxFile = new File(finalXlsxPath); Workbook workBook = getWorkbok(finalXlsxFile); // sheet 對應一個工作頁 Sheet sheet = workBook.getSheetAt(0); //刪除原有數據,除了屬性列 int rowNumber = sheet.getLastRowNum(); for (int i = 1; i <= rowNumber; i++) { Row row = sheet.getRow(i); sheet.removeRow(row); } // 創建文件輸出流,輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效 out = new FileOutputStream(finalXlsxPath); workBook.write(out); //寫一行 for (int j = 0; j < dataList.size(); j++) { Row row = sheet.createRow(j); //寫一列 List<String> datas = dataList.get(j); for (int k=0; k<datas.size(); k++) { row.createCell(k).setCellValue(datas.get(k)); } } // 創建文件輸出流,准備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效 out = new FileOutputStream(finalXlsxPath); workBook.write(out); System.out.println("數據導出成功"); } catch (Exception e) { System.out.println("請創建一個空文件"); e.printStackTrace(); } finally{ try { if(out != null){ out.flush(); out.close(); } } catch (IOException e) { e.printStackTrace(); } } } private static final String EXCEL_XLS = "xls"; private static final String EXCEL_XLSX = "xlsx"; private static Workbook getWorkbok(File file) throws IOException{ Workbook wb = null; FileInputStream in = new FileInputStream(file); if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003 wb = new HSSFWorkbook(in); }else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010 wb = new XSSFWorkbook(in); } return wb; } }
import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List<List<String>> resultList = ExcelUtil.readExcel("H:/data.xlsx"); if (resultList != null) { for (int i = 0; i < resultList.size(); i++) { System.out.print("第" + (i) + "行"); List<String> cellList = resultList.get(i); for (int j = 0; j < cellList.size(); j++) { System.out.print(" " + cellList.get(j)); } System.out.println(); } } //把讀取的結果在寫回去 ExcelUtil.writeExcel(resultList, "H:/result.xlsx"); } }