Java讀取,存寫excel資料
阿新 • • 發佈:2018-12-12
前言所需jar包:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.10-FINAL</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.10-FINAL</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency>
讀取excel檔案內容,支援日期,資料,字元,公式,布林
public class ExcelUtil { public static List<ExcelSheetPO> readExcel(){ List<ExcelSheetPO> sheetPOs = new ArrayList<>(); File file = new File("F:/students.xls"); try{ String fileName = file.getName(); String extName = "."+fileName.substring(fileName.lastIndexOf(".") + 1); Workbook wb = null; if(".xls".equals(extName)){ wb = new HSSFWorkbook(new FileInputStream(file)); }else if(".xlsx".equals(extName)){ wb = new XSSFWorkbook(new FileInputStream(file)); }else{ throw new IllegalArgumentException("Invalid excel version"); } //解析sheet //獲取sheet頁籤 int sheetNum = wb.getNumberOfSheets(); for(int i = 0 ; i < sheetNum ; i ++){ Sheet sheet = wb.getSheetAt(i); Integer rowCount = sheet.getPhysicalNumberOfRows(); List<List<Object>> dataList = new ArrayList<>(); ExcelSheetPO sheetPO = new ExcelSheetPO(); sheetPO.setSheetName(sheet.getSheetName()); sheetPO.setDataList(dataList); int readRowCount = 0; if(rowCount == null || rowCount > sheet.getPhysicalNumberOfRows()){ readRowCount = sheet.getPhysicalNumberOfRows(); }else{ readRowCount = rowCount; } //解析sheet行 for(int j = sheet.getFirstRowNum(); j < readRowCount ; j ++){ Row row = sheet.getRow(j); Integer columnCount = sheet.getRow(j).getPhysicalNumberOfCells(); if(row == null){ continue; } if(row.getFirstCellNum()< 0){ continue; } int readColumnCount = 0; if(columnCount == null || columnCount > row.getLastCellNum()){ readColumnCount = (int)row.getLastCellNum(); }else{ readColumnCount = columnCount; } List<Object> rowValue= new LinkedList<>(); for(int k = 0 ; k < readColumnCount ; k ++){ Cell cell = row.getCell(k); rowValue.add(getCellValue(wb,cell)); } System.out.println(rowValue); dataList.add(rowValue); } sheetPOs.add(sheetPO); } }catch(Exception e){ e.printStackTrace(); } return sheetPOs; } //統一處理每個資料 public static Object getCellValue(Workbook wb,Cell cell){ Object columnValue = null; if(cell !=null){ DecimalFormat df = new DecimalFormat("0");//格式化number //字元 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //數字 DecimalFormat nf = new DecimalFormat("0.00"); switch(cell.getCellType()){ case Cell.CELL_TYPE_STRING: columnValue = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: if ("@".equals(cell.getCellStyle().getDataFormatString())) { columnValue = df.format(cell.getNumericCellValue()); } else if ("General".equals(cell.getCellStyle().getDataFormatString())) { columnValue = nf.format(cell.getNumericCellValue()); } else { columnValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())); } break; case Cell.CELL_TYPE_BOOLEAN: columnValue = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_BLANK: columnValue = ""; break; case Cell.CELL_TYPE_FORMULA: // 格式單元格 FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); evaluator.evaluateFormulaCell(cell); CellValue cellValue = evaluator.evaluate(cell); columnValue = cellValue.getNumberValue(); break; default: columnValue = cell.toString(); } } return columnValue; } }
結果如下:
寫入磁碟操作
package util; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; 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.ss.util.CellRangeAddress; public class ExportExcel { public void getValue(List<WorkSheetDetail> userList,FileOutputStream fout){ try{ //建立工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); List<CellRangeAddress> cellObject = new ArrayList<>(); //建立合併單元格物件 CellRangeAddress callRangeAddress = new CellRangeAddress(0,0,0,7);//起始行,結束行,起始列,結束列 cellObject.add(callRangeAddress); CellRangeAddress callRangeAddress1 = new CellRangeAddress(1,1,0,7); cellObject.add(callRangeAddress1); //班組與時間start CellRangeAddress callRangeAddress20 = new CellRangeAddress(2,2,0,2); cellObject.add(callRangeAddress20); CellRangeAddress callRangeAddress21 = new CellRangeAddress(2,2,3,4); cellObject.add(callRangeAddress21); CellRangeAddress callRangeAddress22 = new CellRangeAddress(2,2,5,7); cellObject.add(callRangeAddress22); //標題 CellRangeAddress callRangeAddress31 = new CellRangeAddress(3,4,0,0); cellObject.add(callRangeAddress31); CellRangeAddress callRangeAddress32 = new CellRangeAddress(3,4,1,1); cellObject.add(callRangeAddress32); CellRangeAddress callRangeAddress33 = new CellRangeAddress(3,4,2,2); cellObject.add(callRangeAddress33); CellRangeAddress callRangeAddress34 = new CellRangeAddress(3,3,3,4); cellObject.add(callRangeAddress34); CellRangeAddress callRangeAddress35 = new CellRangeAddress(3,4,5,5); cellObject.add(callRangeAddress35); CellRangeAddress callRangeAddress36 = new CellRangeAddress(3,4,6,6); cellObject.add(callRangeAddress36); CellRangeAddress callRangeAddress37 = new CellRangeAddress(3,4,7,7); cellObject.add(callRangeAddress37); //金額 CellRangeAddress callRangeAddressnumber1 = new CellRangeAddress(userList.size()+5,userList.size()+5,0,2); cellObject.add(callRangeAddressnumber1); CellRangeAddress callRangeAddressnumber2 = new CellRangeAddress(userList.size()+5,userList.size()+5,3,7); cellObject.add(callRangeAddressnumber2); //負責人 CellRangeAddress callRangeAddressPersion1 = new CellRangeAddress(userList.size()+6,userList.size()+6,0,2); cellObject.add(callRangeAddressPersion1); CellRangeAddress callRangeAddressPersion2 = new CellRangeAddress(userList.size()+6,userList.size()+6,3,4); cellObject.add(callRangeAddressPersion2); CellRangeAddress callRangeAddressPersion3 = new CellRangeAddress(userList.size()+6,userList.size()+6,5,7); cellObject.add(callRangeAddressPersion3); //說明 CellRangeAddress callRangeAddressinfo = new CellRangeAddress(userList.size()+7,userList.size()+7,0,7); cellObject.add(callRangeAddressinfo); CellRangeAddress callRangeAddressinfo1= new CellRangeAddress(userList.size()+8,userList.size()+8,0,7); cellObject.add(callRangeAddressinfo1); CellRangeAddress callRangeAddressinfo2 = new CellRangeAddress(userList.size()+9,userList.size()+9,0,7); cellObject.add(callRangeAddressinfo2); //部專案經理部 HSSFCellStyle headStyle = createCellStyle(workbook,(short)10,false,true); //派工單 HSSFCellStyle erStyle = createCellStyle(workbook,(short)13,true,true); //班組和時間 HSSFCellStyle sanStyle = createCellStyle(workbook,(short)10,false,false); //標題樣式 HSSFCellStyle colStyle = createCellStyle(workbook,(short)10,true,true); //內容樣式 HSSFCellStyle cellStyle = createCellStyle(workbook,(short)10,false,true); //建立工作表 HSSFSheet sheet = workbook.createSheet("派單"); //載入合併單元格物件 for(CellRangeAddress lst:cellObject){ sheet.addMergedRegion(lst); } //設定預設寬列 sheet.setDefaultColumnWidth(15); //建立行 //建立頭標題行,並且設定頭標題 HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); //載入單元格樣式 cell.setCellStyle(headStyle); cell.setCellValue("***專案部"); HSSFRow rower = sheet.createRow(1); HSSFCell celler = rower.createCell(0); //載入單元格樣式 celler.setCellStyle(erStyle); celler.setCellValue("派工單"); HSSFRow rowsan = sheet.createRow(2); HSSFCell cellsan = rowsan.createCell(0); HSSFCell cellsan1 = rowsan.createCell(3); HSSFCell cellsan2 = rowsan.createCell(5); //載入單元格樣式 cellsan.setCellStyle(sanStyle); cellsan.setCellValue("協作單位:x施工一隊"); cellsan1.setCellStyle(sanStyle); cellsan1.setCellValue(""); cellsan2.setCellStyle(sanStyle); cellsan2.setCellValue("時間:2017年 10月 20日"); //建立列標題,並且設定列標題 HSSFRow row2 = sheet.createRow(3); String[] titles = {"序號","工作內容","用工總人數","工日數","","單價(元)","金額(元)","備註"}; for(int i = 0 ; i < titles.length;i ++){ HSSFCell cell2 = row2.createCell(i); //載入單元格樣式 cell2.setCellStyle(colStyle); cell2.setCellValue(titles[i]); } HSSFRow rowfour = sheet.createRow(4); String[] titlefour = {"普工","技工"}; for(int i = 0 ; i < titlefour.length; i ++){ HSSFCell cell2 = rowfour.createCell(i+3); cell2.setCellStyle(colStyle); cell2.setCellValue(titlefour[i]); } //操作單元格,將使用者列表寫入excel if(userList != null){ int i = 1; for(int j = 0 ;j < userList.size(); j ++){ HSSFRow row3 = sheet.createRow(j+5); HSSFCell cell0 = row3.createCell(0); cell0.setCellStyle(cellStyle); cell0.setCellValue(i++); HSSFCell cell1 = row3.createCell(1); cell1.setCellStyle(cellStyle); cell1.setCellValue(userList.get(j).getWorkCtx()); HSSFCell cell2 = row3.createCell(2); cell2.setCellStyle(cellStyle); cell2.setCellValue(userList.get(j).getTotalHumanDays()); HSSFCell cell3 = row3.createCell(3); cell3.setCellStyle(cellStyle); cell3.setCellValue(userList.get(j).getGwnNum()); HSSFCell cell4 = row3.createCell(4); cell4.setCellStyle(cellStyle); cell4.setCellValue(userList.get(j).getTmnNum()); HSSFCell cell5 = row3.createCell(5); cell5.setCellStyle(cellStyle); cell5.setCellValue(userList.get(j).getTotalHumanDays()); HSSFCell cell6 = row3.createCell(6); cell6.setCellStyle(cellStyle); cell6.setCellValue(userList.get(j).getUnitAmount()); HSSFCell cell7 = row3.createCell(7); cell7.setCellStyle(cellStyle); cell7.setCellValue(userList.get(j).getUnitPrice()); } } HSSFRow rownumber = sheet.createRow(userList.size()+5); HSSFCell cellnumber = rownumber.createCell(0); HSSFCell cellnumber1 = rownumber.createCell(3); //載入單元格樣式 cellnumber.setCellStyle(sanStyle); cellnumber.setCellValue("金額合計(大寫"); cellnumber1.setCellStyle(sanStyle); cellnumber1.setCellValue("¥ 78 元;大寫:柒拾捌元整"); HSSFRow rowpersion = sheet.createRow(userList.size()+6); HSSFCell cellpersion = rowpersion.createCell(0); HSSFCell cellpersion1 = rowpersion.createCell(3); HSSFCell cellpersion2 = rowpersion.createCell(5); //載入單元格樣式 cellpersion.setCellStyle(sanStyle); cellpersion.setCellValue("協作單位負責人:"); cellpersion1.setCellStyle(sanStyle); cellpersion1.setCellValue("經辦人:"); cellpersion2.setCellStyle(sanStyle); cellpersion2.setCellValue("部門負責人:"); HSSFRow rowinfo = sheet.createRow(userList.size()+7); HSSFCell cellinfo = rowinfo.createCell(0); cellinfo.setCellStyle(sanStyle); cellinfo.setCellValue("說明:1、本標工單一式兩聯,第一聯為派工人存根,第二聯用作結算"); HSSFRow rowinfo1 = sheet.createRow(userList.size()+8); HSSFCell cellinfo1 = rowinfo1.createCell(0); cellinfo1.setCellStyle(sanStyle); cellinfo1.setCellValue("2、本標工單必須在用工當日籤認,否則不予認可;三日內交合同處彙總"); HSSFRow rowinfo2 = sheet.createRow(userList.size()+9); HSSFCell cellinfo2 = rowinfo2.createCell(0); cellinfo2.setCellStyle(sanStyle); cellinfo2.setCellValue("3、工日數填寫精確到半個工日"); //輸出 workbook.write(fout); }catch(Exception e ){ e.printStackTrace(); } } //單元格樣式 private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook,short fontsize,boolean flag,boolean flag1){ HSSFCellStyle style = workbook.createCellStyle(); //是否水平居中 if(flag1){ style.setAlignment(HSSFCellStyle.ALIGN_CENTER); } style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //建立字型 HSSFFont font = workbook.createFont(); //是否加粗字型 if(flag){ font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); } //載入字型 style.setFont(font); return style; } public static void main(String[] args){ //模擬部分資料 List<WorkSheetDetail> detail = new ArrayList<>(); WorkSheetDetail d1 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34"); WorkSheetDetail d2 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34"); WorkSheetDetail d3 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34"); detail.add(d1); detail.add(d2); detail.add(d3); try{ FileOutputStream fout = new FileOutputStream("F:/students.xls"); new ExportExcel().getValue(detail, fout); fout.close(); }catch(Exception e){ e.printStackTrace(); } } }
package util;
public class WorkSheetDetail {
//工作內容
private String workCtx;
//用工總人數
private Float totalHumanDays;
//普工
private Integer gwnNum;
//技工
private Integer tmnNum;
//單價
private Float unitPrice;
//金額
private Float unitAmount;
//備註
private String notes;
public WorkSheetDetail(String workCtx, Float totalHumanDays,
Integer gwnNum, Integer tmnNum, Float unitPrice, Float unitAmount,
String notes) {
super();
this.workCtx = workCtx;
this.totalHumanDays = totalHumanDays;
this.gwnNum = gwnNum;
this.tmnNum = tmnNum;
this.unitPrice = unitPrice;
this.unitAmount = unitAmount;
this.notes = notes;
}
public String getWorkCtx() {
return workCtx;
}
public void setWorkCtx(String workCtx) {
this.workCtx = workCtx;
}
public Float getTotalHumanDays() {
return totalHumanDays;
}
public void setTotalHumanDays(Float totalHumanDays) {
this.totalHumanDays = totalHumanDays;
}
public Integer getGwnNum() {
return gwnNum;
}
public void setGwnNum(Integer gwnNum) {
this.gwnNum = gwnNum;
}
public Integer getTmnNum() {
return tmnNum;
}
public void setTmnNum(Integer tmnNum) {
this.tmnNum = tmnNum;
}
public Float getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Float unitPrice) {
this.unitPrice = unitPrice;
}
public Float getUnitAmount() {
return unitAmount;
}
public void setUnitAmount(Float unitAmount) {
this.unitAmount = unitAmount;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
注:本文寫入時候的資料為固定資料,實戰中可以用讀取的資料進行替換