原文地址https://blog.csdn.net/qq_33685734/article/details/77737387
原文地址https://www.cnblogs.com/chenyq/p/5530970.html
java寫入excel文件poi,支持xlsx與xls,沒有文件自動創建
package com.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; 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.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.exception.SimpleException; /** * 從excel讀取數據/往excel中寫入 excel有表頭,表頭每列的內容對應實體類的屬性 * * @author nagsh * */ public class ExcelManage { public static void main(String[] args) throws IOException { String path = "E:/"; String fileName = "被保險人員清單(新增)04"; String fileType = "xlsx"; List<InsuraceExcelBean> list = new ArrayList<>(); for(int i=0; i<6; i++){ InsuraceExcelBean bean = new InsuraceExcelBean(); bean.setInsuraceUser("test"+i); bean.setBankCardId("4444444444"+i+","+"55544444444444"+i+","+"999999999999999"+i); bean.setIdCard("666666"+i); bean.setBuyTime("2016-05-06"); bean.setInsEndTime("2016-05-07"); bean.setInsStartTime("2017-05-06"); bean.setMoney("20,000"); bean.setType("儲蓄卡"); list.add(bean); } String title[] = {"被保險人姓名","身份證號","賬戶類型","銀行卡號","保險金額(元)","購買時間","保單生效時間","保單失效時間"}; // createExcel("E:/被保險人員清單(新增).xlsx","sheet1",fileType,title); writer(path, fileName, fileType,list,title); } @SuppressWarnings("resource") public static void writer(String path, String fileName,String fileType,List<InsuraceExcelBean> list,String titleRow[]) throws IOException { Workbook wb = null; String excelPath = path+File.separator+fileName+"."+fileType; File file = new File(excelPath); Sheet sheet =null; //創建工作文檔對象 if (!file.exists()) { if (fileType.equals("xls")) { wb = new HSSFWorkbook(); } else if(fileType.equals("xlsx")) { wb = new XSSFWorkbook(); } else { throw new SimpleException("文件格式不正確"); } //創建sheet對象 sheet = (Sheet) wb.createSheet("sheet1"); OutputStream outputStream = new FileOutputStream(excelPath); wb.write(outputStream); outputStream.flush(); outputStream.close(); } else { if (fileType.equals("xls")) { wb = new HSSFWorkbook(); } else if(fileType.equals("xlsx")) { wb = new XSSFWorkbook(); } else { throw new SimpleException("文件格式不正確"); } } //創建sheet對象 if (sheet==null) { sheet = (Sheet) wb.createSheet("sheet1"); } //添加表頭 Row row = sheet.createRow(0); Cell cell = row.createCell(0); row.setHeight((short) 540); cell.setCellValue("被保險人員清單"); //創建第一行 CellStyle style = wb.createCellStyle(); // 樣式對象 // 設置單元格的背景顏色爲淡藍色 style.setFillForegroundColor(HSSFColor.PALE_BLUE.index); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直 style.setAlignment(CellStyle.ALIGN_CENTER);// 水平 style.setWrapText(true);// 指定當單元格內容顯示不下時自動換行 cell.setCellStyle(style); // 樣式,居中 Font font = wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setFontHeight((short) 280); style.setFont(font); // 單元格合併 // 四個參數分別是:起始行,起始列,結束行,結束列 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7)); sheet.autoSizeColumn(5200); row = sheet.createRow(1); //創建第二行 for(int i = 0;i < titleRow.length;i++){ cell = row.createCell(i); cell.setCellValue(titleRow[i]); cell.setCellStyle(style); // 樣式,居中 sheet.setColumnWidth(i, 20 * 256); } row.setHeight((short) 540); //循環寫入行數據 for (int i = 0; i < list.size(); i++) { row = (Row) sheet.createRow(i+2); row.setHeight((short) 500); row.createCell(0).setCellValue(( list.get(i)).getInsuraceUser()); row.createCell(1).setCellValue(( list.get(i)).getIdCard()); row.createCell(2).setCellValue(( list.get(i)).getType()); row.createCell(3).setCellValue(( list.get(i)).getBankCardId()); row.createCell(4).setCellValue(( list.get(i)).getMoney()); row.createCell(5).setCellValue(( list.get(i)).getBuyTime()); row.createCell(6).setCellValue(( list.get(i)).getInsStartTime()); row.createCell(7).setCellValue(( list.get(i)).getInsEndTime()); } //創建文件流 OutputStream stream = new FileOutputStream(excelPath); //寫入數據 wb.write(stream); //關閉文件流 stream.close(); } }
============================================================================================================================================================================================================================================================================================================================================================================================================
//定義表頭
String[] title={"序號","姓名","年齡"};
//創建excel工作簿
HSSFWorkbook workbook=new HSSFWorkbook();
//創建工作表sheet
HSSFSheet sheet=workbook.createSheet();
//創建第一行
HSSFRow row=sheet.createRow(0);
HSSFCell cell=null;
//插入第一行數據的表頭
for(int i=0;i<title.length;i++){
cell=row.createCell(i);
cell.setCellValue(title[i]);
}
//寫入數據
for (int i=1;i<=10;i++){
HSSFRow nrow=sheet.createRow(i);
HSSFCell ncell=nrow.createCell(0);
ncell.setCellValue(""+i);
ncell=nrow.createCell(1);
ncell.setCellValue("user"+i);
ncell=nrow.createCell(2);
ncell.setCellValue("24");
}
//創建excel文件
File file=new File("f://poi.xlsx");
try {
file.createNewFile();
//將excel寫入
FileOutputStream stream= FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
在maven倉庫中導入jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>