1. 創建Excel
1.1 創建新Excel工作簿
引入poi依賴
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.3</version>
</dependency>
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileOutputStream;
public class Demo01 { public static void main(String[] args) throws Exception { // 創建一個工作簿 Workbook wb = new HSSFWorkbook(); // 創建輸出流 FileOutputStream fileOutputStream = new FileOutputStream("E:\\java\\poi\\poi\\創建一個Excel工作簿.xls"); wb.write(fileOutputStream); // 工作簿寫出流 wb.close(); }
}
運行代碼
?1.2 創建新sheet頁
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileOutputStream;
public class Demo02 { public static void main(String[] args) throws Exception { // 創建一個工作簿 Workbook wb = new HSSFWorkbook(); // 創建一個sheet頁 wb.createSheet("這是第一個sheet的名字"); wb.createSheet("這是第二個sheet的名字"); // 創建輸出流 FileOutputStream fileOutputStream = new FileOutputStream("E:\\java\\poi\\poi\\創建sheet.xls"); // 工作簿寫出流 wb.write(fileOutputStream); wb.close(); }
}
運行代碼
1.3 創建單元格
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileOutputStream;
public class Demo03 { public static void main(String[] args) throws Exception { // 創建一個工作簿 Workbook wb = new HSSFWorkbook(); // 創建一個sheet頁 Sheet sheet = wb.createSheet("這是第一個sheet的名字"); // 創建單元格并設置內容 // 創建第一行 Row row = sheet.createRow(0); row.createCell(0).setCellValue(1); // 第一列 row.createCell(1).setCellValue(1.2); // 第二列 row.createCell(2).setCellValue("字符串"); // 第三列 // 創建輸出流 FileOutputStream fileOutputStream = new FileOutputStream("E:\\java\\poi\\poi\\創建sheet.xls"); // 工作簿寫出流 wb.write(fileOutputStream); wb.close(); }
}
運行代碼
2. 創建時間格式單元格
2.1 創建一個時間格式的單元格
Java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
import java.util.Date;/*** @Description: 創建時間格式單元格* @author: lh*/
public class Demo04 {public static void main(String[] args) throws Exception {Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("第一個sheet頁");Row row = sheet.createRow(0);row.createCell(0).setCellValue(new Date());// 設置單元格日期格式CreationHelper creationHelper = workbook.getCreationHelper();CellStyle cellStyle = workbook.createCellStyle();// 單元格樣式cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss"));Cell cell = row.createCell(1);cell.setCellValue(new Date());cell.setCellStyle(cellStyle);FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿");workbook.write(fileOutputStream);workbook.close();}
}
運行結果
2.2 遍歷工作簿的行和列并獲取單元格內容
java代碼
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;/*** @Description: 遍歷單元格* @author: lh*/
public class Demo05 {public static void main(String[] args) throws Exception {FileInputStream fileInputStream = new FileInputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");POIFSFileSystem fs = new POIFSFileSystem(fileInputStream);HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fs);HSSFSheet sheet = hssfWorkbook.getSheetAt(0);if (sheet == null) {return;}// 遍歷rowfor (int i = 0; i <= sheet.getLastRowNum(); i++) {HSSFRow row = sheet.getRow(i);if (row == null) {continue;}// 遍歷cellfor (int j = 0; j <= row.getLastCellNum(); j++) {if (row.getCell(j) == null) {continue;}System.out.print(" " + getValue(row.getCell(j)));}System.out.println();}}/*** 獲取不同類型單元格類型的值 * @param cell 單元格* @return 單元格內容*/private static String getValue(HSSFCell cell) {switch (cell.getCellType()) {case NUMERIC:return Double.toString(cell.getNumericCellValue());case BOOLEAN:return Boolean.toString(cell.getBooleanCellValue());case FORMULA:return cell.getCellFormula();case STRING:return cell.getStringCellValue();// Add cases for other cell types as needed...default:System.out.println("Unsupported cell type");return "";}}
}
運行結果
2.4 文本提取
Java代碼
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;/*** @Description: 文本提取* @author: lh*/
public class Demo06 {public static void main(String[] args) throws Exception {FileInputStream fileInputStream = new FileInputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");POIFSFileSystem fs = new POIFSFileSystem(fileInputStream);HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fs);ExcelExtractor excelExtractor = new ExcelExtractor(hssfWorkbook);excelExtractor.setIncludeSheetNames(false); //不需要sheet頁System.out.println(excelExtractor.getText());fileInputStream.close();fs.close();}
}
運行結果?
3. 單元格處理
3.1 單元格對齊方式
Java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileOutputStream;import org.apache.poi.ss.usermodel.*;/*** @Description: 單元格對齊方式* @author: lh*/
public class Demo07 {public static void main(String[] args) throws Exception {Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("第一個sheet頁");Row row = sheet.createRow(0);row.setHeightInPoints(30);// 創建單元格對齊方式createCell(workbook, row, (short) 0, HorizontalAlignment.CENTER, VerticalAlignment.CENTER, "單元格對齊方式1");createCell(workbook, row, (short) 1, HorizontalAlignment.LEFT, VerticalAlignment.BOTTOM, "單元格對齊方式2");createCell(workbook, row, (short) 2, HorizontalAlignment.RIGHT, VerticalAlignment.TOP, "單元格對齊方式3");FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");workbook.write(fileOutputStream);workbook.close();}private static void createCell(Workbook workbook, Row row, short column, HorizontalAlignment align, VerticalAlignment valign, String value) {Cell cell = row.createCell(column);CellStyle cellStyle = workbook.createCellStyle();cellStyle.setAlignment(align);cellStyle.setVerticalAlignment(valign);cell.setCellValue(value);cell.setCellStyle(cellStyle);}
}
運行結果
3.2 單元格邊框處理
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;import java.io.FileOutputStream;/*** @Description: 單元格邊框處理* @author: lh*/
public class Demo08 {public static void main(String[] args) throws Exception{Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("第一個sheet頁");Row row = sheet.createRow(1);row.setHeightInPoints(30);Cell cell = row.createCell(1);cell.setCellValue("單元格邊框處理");// 單元格邊框處理CellStyle cellStyle = workbook.createCellStyle();cellStyle.setBorderTop(BorderStyle.THIN); // 頂部邊框樣式cellStyle.setTopBorderColor(IndexedColors.RED.getIndex()); // 頂部邊框顏色cellStyle.setBorderLeft(BorderStyle.MEDIUM); // 左邊邊框樣式cellStyle.setLeftBorderColor(IndexedColors.BLUE.getIndex()); // 左邊邊框顏色cellStyle.setBorderRight(BorderStyle.MEDIUM); // 右邊邊框樣式cellStyle.setRightBorderColor(IndexedColors.GREEN.getIndex()); // 右邊邊框顏色cellStyle.setBorderBottom(BorderStyle.MEDIUM); // 底部邊框樣式cellStyle.setBottomBorderColor(IndexedColors.BROWN.getIndex()); // 底部邊框顏色cell.setCellStyle(cellStyle);FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");workbook.write(fileOutputStream);workbook.close();}
}
運行結果
3.3 單元格填充色和顏色操作
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;/*** @Description: 設置單元格顏色* @author: lh*/
public class Demo09 {public static void main(String[] args) throws Exception{Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("第一個sheet頁");Row row = sheet.createRow(1);row.setHeightInPoints(30);// 設置單元格顏色Cell cell = row.createCell(1);cell.setCellValue("單元格邊框處理");CellStyle cellStyle = workbook.createCellStyle();cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); //背景色cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell.setCellStyle(cellStyle);Cell cell1 = row.createCell(2);cell1.setCellValue("單元格邊框處理1");CellStyle cellStyle1 = workbook.createCellStyle();cellStyle1.setFillForegroundColor(IndexedColors.RED.getIndex()); //前景色cellStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell1.setCellStyle(cellStyle1);FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");workbook.write(fileOutputStream);workbook.close();}
}
運行結果
3.4 單元格合并
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;import java.io.FileOutputStream;/*** @Description: 單元格合并* @author: lh*/
public class Demo10 {public static void main(String[] args) throws Exception{Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("第一個sheet頁");Row row = sheet.createRow(1);row.setHeightInPoints(30);// 合并單元格Cell cell = row.createCell(1);cell.setCellValue("合并單元格");sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 3));FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");workbook.write(fileOutputStream);workbook.close();}
}
運行結果
4. 字體處理
4.1 字體處理
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;import java.io.FileOutputStream;/*** @Description: 字體處理* @author: lh*/
public class Demo11 {public static void main(String[] args) throws Exception{Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("第一個sheet頁");Row row = sheet.createRow(1);row.setHeightInPoints(30);// 創建一個字體處理類Font font = workbook.createFont();font.setFontHeightInPoints((short) 24);font.setFontName("宋體");font.setItalic(true);CellStyle cellStyle = workbook.createCellStyle();cellStyle.setFont(font);Cell cell = row.createCell((short) 1);cell.setCellValue("hello world");cell.setCellStyle(cellStyle);FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");workbook.write(fileOutputStream);workbook.close();}
}
運行結果
4.2?單元格中使用換行
java代碼
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;import java.io.FileOutputStream;/*** @Description: 單元格換行* @author: lh*/
public class Demo12 {public static void main(String[] args) throws Exception{Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("第一個sheet頁");Row row = sheet.createRow(1);row.setHeightInPoints(30);Cell cell = row.createCell(2);cell.setCellValue("我要換行 \n 成功了嗎?");CellStyle cellStyle = workbook.createCellStyle();// 設置可以換行cellStyle.setWrapText(true);cell.setCellStyle(cellStyle);FileOutputStream fileOutputStream = new FileOutputStream("/Users/lihui/Documents/Java/poi/工作簿.xls");workbook.write(fileOutputStream);workbook.close();}
}
運行結果
5. 綜合示例
// excel導入
@Transactional
public Result<?> import(Model model) throws IOException
{// 獲取上傳附件String attId = attachFileAppService.handleAttFiles(Collections.singletonList(model));if (StringUtil.isEmpty(attId)){throw new NormalRuntimeException(ModelCodeConstants.ATTACHMENT_LOST);}Workbook workbook = null;InputStream data = null;try{// 獲取Excel文件流UploadAttachFileInfo uploadAttachFileInfo = attachFileAppService.downloadFile(attId);// 文件格式校驗checkType(uploadAttachFileInfo);data = uploadAttachFileInfo.getData();workbook = ExcelUtils.getExcelWorkbook(data);Sheet sheet = workbook.getSheet(ModelCodeConstants."讀取sheet的名字");if (CommonUtil.isEmpty(sheet)){return Result.fail(ModelCodeConstants.ERROR_TITLE);}// 表頭檢驗checkTitle(sheet);// 空表檢驗if (sheet.getLastRowNum() == 0 && sheet.getPhysicalNumberOfRows() == 1){return Result.fail(ModelCodeConstants.EMPTY_FILE);}// 數據導入- 從第四行開始int startRowIndex = 4;Iterator<Row> iterator = sheet.iterator();for (int i = 0; i < startRowIndex; i++){iterator.next();}List<XXX> list = new ArrayList<>();List<XXX> errList = new ArrayList<>();while (iterator.hasNext()){Row row = iterator.next();String xxx = getValue(row.getCell(0));String yyy = getValue(row.getCell(1));String zzz = getValue(row.getCell(2));String aaa = getValue(row.getCell(3));// 導入數據規則校驗StringJoiner joiner = new StringJoiner(",");checkBody(xxx, yyy, zzz, aaa, joiner);XXX err = new XXX();if (joiner.length() != 0){err.setErrMsg(joiner);// 錯誤信息添加errList.add(err);} else{XXX x = new XXX();// 入庫信息添加list.add(x);// 數據入庫service.add();}}if (CommonUtil.isNotEmpty(errList)){//把原信息和錯誤信息寫回去String uuid = writeErrExcel(errList);return Result.fail("數據導入不成功,點擊下載錯誤信息!").setData(uuid);}} catch (Exception e){e.printStackTrace();return Result.fail(e.getMessage());} finally{assert workbook != null;workbook.close();data.close();}return Result.success();
}/**
* 文件格式校驗 以xls或者xlsx結尾
*/
private static void checkType(UploadAttachFileInfo uploadAttachFileInfo)
{AttachFileInfo fileInfo;fileInfo = uploadAttachFileInfo.getFileInfo();if (!fileInfo.getFileName().endsWith(ModelCodeConstants.EXCEL_SUFFIX_XLS)&& !fileInfo.getFileName().endsWith(ModelCodeConstants.EXCEL_SUFFIX_XLSX)){throw new NormalRuntimeException("文件格式有誤!");}
}/**
* 校驗表頭是否正確
*/
private static void checkTitle(Iterator<Row> rowIterator)
{Row headerRow = rowIterator.next();Cell xxxx = headerRow.getCell(0);Cell yyyy = headerRow.getCell(1);if (!"xxxx".equals(xxxx.getStringCellValue()) || !"yyyy".equals(yyyy.getStringCellValue())){throw new NormalRuntimeException(ModelCodeConstants.ERROR_TITLE);}
}/**
* 填寫錯誤信息excel
*/
private String writeErrExcel(List<XXX> errList) throws Exception
{// 讀取錯誤信息模板String rootPath = SpringContextConfig.getOptRootPath();String filePath = rootPath + FilePathConst.TEMPLATE_FILE_PATH + FileNameConst.WBS_CODE_ERROR_FILE_NAME;File file = ResourceUtils.getFile(filePath);InputStream inputStream = Files.newInputStream(file.toPath());// 處理導入錯誤信息數據Workbook workbook = ExcelUtils.getExcelWorkbook(inputStream);Sheet sheet = workbook.getSheet(ModelCodeConstants.TEMPLATE_ESTIMATE_DETAILS);int startRow = 4; // 從第五行開始寫入數據CellStyle cellStyle = workbook.createCellStyle();cellStyle.setWrapText(true); // 自動換行for (int i = startRow; i < errList.size() + startRow; i++){Row row = sheet.createRow(i);XXX rowData = errList.get(i - startRow); // 獲取當前行數據String xxx = rowData.getLevel();String yyy = rowData.getWbsCode();String zzz = rowData.getWbsDescribe();String aaa = rowData.getWbsAmount();String errMsg = rowData.getErrMsg();row.createCell(0).setCellValue(xxx);row.createCell(1).setCellValue(yyy);row.createCell(2).setCellValue(zzz);row.getCell(2).setCellStyle(cellStyle);row.createCell(3).setCellValue(aaa);row.createCell(4).setCellValue(errMsg);row.getCell(4).setCellStyle(cellStyle);}// Excel文件寫到目標路徑下String uuid = CommonUtil.getUUID();String distPath = AttachServerConfig.AttachServerTempPath + "/" + FilePathConst.ERROR_FILE_PATH + "/" + uuid+ "/" + FileNameConst.WBS_CODE_ERROR_FILE_NAME;ExcelWriter write = new ExcelWriter(sheet);write.setDestFile(new File(distPath));write.flush();write.close();InputStream distStream = new FileInputStream(distPath);uuid = attachFileAppService.uploadFile(distStream, FileNameConst.WBS_CODE_ERROR_FILE_NAME,FileModelTypeEnum.導入失敗信息.getModel(), uuid, "xlsx");return uuid;
}
// 枚舉常量類
public interface ModelCodeConstants
{public final String ATTACHMENT_LOST = "導入附件丟失或未找到,請重新上傳!";public final String ERROR_TITLE = "表頭信息錯誤,請使用標準模板文件導入!";public final String EMPTY_FILE = "上傳文件內容為空,請確認!";}
// excel工具類
public class ExcelUtils
{ /*** 讀取工作區域,傳入流文件* @param input* @return*/public static Workbook getExcelWorkbook(InputStream input){Workbook workbook = null;try{workbook = WorkbookFactory.create(input);} catch (EncryptedDocumentException | InvalidFormatException | IOException e){e.printStackTrace();}return workbook;}/*** 獲取不同類型單元格類型的值 * @param cell 單元格* @return 單元格內容*/private static String getValue(HSSFCell cell) {switch (cell.getCellType()) {case NUMERIC:return Double.toString(cell.getNumericCellValue());case BOOLEAN:return Boolean.toString(cell.getBooleanCellValue());case FORMULA:return cell.getCellFormula();case STRING:return cell.getStringCellValue();// Add cases for other cell types as needed...default:System.out.println("Unsupported cell type");return "";}}
}