解析Excel表(總結)
1.解析.xls和.xlsx格式表格
程式碼:
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);Workbook wb = null;
if ("xls".equals(prefix)) {
FileInputStream fis = null;
try {
fis = new FileInputStream((File) file);
wb = new HSSFWorkbook(fis);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("xlsx".equals(prefix)) {
try {
wb = new XSSFWorkbook((File) file);
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
}
//開始解析
Sheet sheet = wb.getSheetAt(0); //讀取sheet 0
int firstRowIndex = sheet.getFirstRowNum() + 1; //第一行是列名,所以不讀
int lastRowIndex = sheet.getLastRowNum();
System.out.println("firstRowIndex: " + firstRowIndex);
System.out.println("lastRowIndex: " + lastRowIndex);
for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍歷行
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null) {
Cell xenditId = row.getCell(0);
Cell status = row.getCell(1);
Cell type = row.getCell(2);
Cell createdDate = row.getCell(3);
Cell createdDateIso = row.getCell(5);
Cell reference = row.getCell(6);
Cell amount = row.getCell(9);
Cell name = row.getCell(11);
Cell bank_code = row.getCell(12);
Cell accountNumber = row.getCell(13);
Timestamp xenditTime = XenditCallBackTimeConvertUtil.convertXenditCallBackTime(String.valueOf(createdDate));
Timestamp createTime = new Timestamp(System.currentTimeMillis());
XenditBill xenditBill = new XenditBill(String.valueOf(xenditId), String.valueOf(status),
String.valueOf(type), String.valueOf(createdDate), String.valueOf(createdDateIso),
String.valueOf(reference), Double.parseDouble(amount.toString()), String.valueOf(name), String.valueOf(bank_code),
String.valueOf(accountNumber), xenditTime, createTime, null);
xenditBillService.saveXenditBill(xenditBill);
}
}
2.解析.csv格式Excel表格
運用FastDFS:
@RequestMapping("/upload") public JsonResult uploadXenditExcel(MultipartFile file) { if (file.isEmpty()) { return JsonResult.buildError(); } String filePath = ""; try { filePath = fastDFSService.uploadFile(file.getInputStream(), file.getSize(), file.getOriginalFilename()); } catch(Exception e) { log.error("[upload] 上傳檔案異常 e={}", e); return JsonResult.buildError(); } //將filePath 存入資料庫 Timestamp time = new Timestamp(System.currentTimeMillis()); FileUrl fileUrl = new FileUrl(file.getOriginalFilename(),filePath,time,time); xenditBillService.saveFileUrl(fileUrl); return JsonResult.buildSuccess(filePath); } /** * 分析xendit表,建立流水庫 * * @return */ @RequestMapping("/analyseXendit") public JsonResult analyseXenditExcel() { //資料庫查詢最新的一條記錄 path String path = xenditBillService.getLatestPath(); byte[] fileByte = null; try { fileByte = fastDFSService.downloadFile(path); } catch (Exception e) { log.error("analyseXenditExcel 異常 e={}", e); return JsonResult.buildError(); } String fileName = "xenditCvs".concat(Long.toString(System.currentTimeMillis())); File file = new File(this.filePath.concat("/").concat(fileName)); if (file.exists()) { file.delete(); } byte2File(fileByte, this.filePath, fileName); Boolean flag = true; try { ArrayList<String[]> csvFileList = new ArrayList<String[]>(); CsvReader reader = new CsvReader(this.filePath.concat("/").concat(fileName), ',', Charset.forName("UTF-8")); reader.readHeaders(); while (reader.readRecord()) { csvFileList.add(reader.getValues()); } reader.close(); for (int row = 0; row < csvFileList.size(); row++) { String type = csvFileList.get(row)[2]; if ("DIRECT_DISBURSEMENT_CREATED".equals(type) || "VIRTUAL_ACCOUNT_SETTLEMENT".equals(type)) { // 取得第row行第0列的資料 String xenditId = csvFileList.get(row)[0]; String status = csvFileList.get(row)[1]; String createdDate = csvFileList.get(row)[3]; String createdDateIso = csvFileList.get(row)[5]; String reference = csvFileList.get(row)[6]; String amount = csvFileList.get(row)[9]; String name = csvFileList.get(row)[11]; String bank_code = csvFileList.get(row)[12]; String accountNumber = csvFileList.get(row)[13]; Timestamp xenditTime = null; if (StringUtils.isNotBlank(createdDateIso)) { xenditTime = XenditCallBackTimeConvertUtil.convertXenditCallBackTime(createdDateIso); } Timestamp time = new Timestamp(System.currentTimeMillis()); XenditBill xenditBill = new XenditBill(xenditId, status, type, createdDate, createdDateIso, reference, new BigDecimal(amount), name, bank_code, accountNumber, xenditTime, time, time); xenditBillService.saveXenditBill(xenditBill); } } } catch (Exception e) { flag = false; log.error("analyseXendit error e={}", e); } return flag == true ? JsonResult.buildSuccess() : JsonResult.buildError(); } private void byte2File(byte[] buf, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if (!dir.exists() && dir.isDirectory()) { dir.mkdirs(); } file = new File(filePath + File.separator + fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { log.error("byte2File error e={}", e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { log.error("byte2File error e={}", e); } } } } }
3.解析以上格式
程式碼:
public JsonResult getXenditBill(MultipartFile file) {
Boolean flate = true;
if (!file.isEmpty()) {
try {
File f = File.createTempFile("tmp", null);
file.transferTo(f);
f.deleteOnExit();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
String item[] = line.split(",");
String type = item[2];
if ("DIRECT_DISBURSEMENT_CREATED".equals(type) || "VIRTUAL_ACCOUNT_SETTLEMENT".equals(type)) {
String xenditId = item[0];
String status = item[1];
String contact = item[3] + "," + item[4];
String createdDate = contact.substring(1, contact.length() - 1);
String createdDateIso = item[6];
String reference = item[7];
String amount = item[10];
String name = item[12];
String bank_code = item[13];
String accountNumber = item[14];
Timestamp xenditTime = XenditCallBackTimeConvertUtil.convertXenditCallBackTime(createdDateIso);
Timestamp time = new Timestamp(System.currentTimeMillis());
XenditBill xenditBill = new XenditBill(xenditId, status, type, createdDate, createdDateIso,
reference, Double.parseDouble(amount), name, bank_code, accountNumber, xenditTime, time, time);
xenditBillService.saveXenditBill(xenditBill);
}
}
} catch (Exception e) {
flate = false;
e.printStackTrace();
}
} else {
flate = false;
}
return flate == true ? JsonResult.buildSuccess() : JsonResult.buildError();
}
}