今天要用spring batch 读excel文件,之前只读过csv文件和txt文件,然后百度一下发现没有spring batch读excel文件的(可能有只是我没看到),然后就想把它转为txt格式的。
package cn.sunline.hnls.facility.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.NumberToTextConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.monitorjbl.xlsx.StreamingReader;
/**
* excel转换为txt文件(大批量)
*
*/
public class ExcelToTxt {
private static Logger logger = LoggerFactory.getLogger(ExcelToTxt.class);
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";
public static void checkExcelVaild(File file) throws Exception{
if(!file.exists()){
throw new Exception("文件不存在");
}
if(!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))){
throw new Exception("文件不是Excel");
}
}
/**
*
* @param excel文件(支持所有版本)
* @param 需要转换的txt文件
* @param skip 需要跳过的行数
* @param maxColumnNum 读取到的最大列数
* @param lineSeparator 导出txt文件分隔符
*/
public static void excelToTxt(File excelFile, File txtFile,int skip,int maxColumnNum,String lineSeparator){
logger.debug("excel转换为txt文件开始");
System.out.println("数据转换开始!");
PrintWriter pw=null;
try {
checkExcelVaild(excelFile);
Workbook wb = null;
FileInputStream in = new FileInputStream(excelFile);
wb = StreamingReader.builder()
.rowCacheSize(100) //缓存到内存中的行数,默认是10
.bufferSize(4096) //读取资源时,缓存到内存的字节大小,默认是1024
.open(in); //打开资源,
Sheet sheet = wb.getSheetAt(0);
FileOutputStream fileOutputStream = new FileOutputStream(txtFile);
OutputStreamWriter outputStream = new OutputStreamWriter(fileOutputStream);
pw = new PrintWriter(outputStream);
int count = 0;
for (Row row : sheet) {
try {
//是否跳行
if(count < skip ) {
count++;
continue;
}
if(row == null)continue;
for (int i = 0; i < maxColumnNum; i++) {
Cell cell = row.getCell(i);
if(cell == null)continue;
String cellValue = getCellValue(cell);
if(StringUtils.isNotBlank(cellValue)){
if(i>=0&&i<maxColumnNum-1){
pw.print(cellValue);
pw.print(lineSeparator);
System.out.print(cellValue + "t");
}else if(i==maxColumnNum-1){
pw.println(cellValue);
pw.flush();
System.out.println(cellValue + "t");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("数据转换完毕!");
logger.debug("excel转换为txt文件结束");
} catch (Exception e){
e.printStackTrace();
}finally {
pw.close();
}
}
private static String getCellValue(Cell cell) {
String cellvalue = "";
if (cell!= null) {
// 判断当前Cell的Type
switch (cell.getCellType()) {
// 如果当前Cell的Type为NUMERIC
case Cell.CELL_TYPE_NUMERIC: {
// 判断当前的cell是否为Date
if (DateUtil.isCellDateFormatted(cell)) { //先注释日期类型的转换,在实际测试中发现HSSFDateUtil.isCellDateFormatted(cell)只识别2014/02/02这种格式。
// 如果是Date类型则,取得该Cell的Date值 // 对2014-02-02格式识别不出是日期格式
Date date = cell.getDateCellValue();
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
cellvalue= formater.format(date);
} else { // 如果是纯数字
// 取得当前Cell的数值
cellvalue = NumberToTextConverter.toText(new BigDecimal(cell.getNumericCellValue()).setScale(4, BigDecimal.ROUND_HALF_DOWN).doubleValue());
}
break;
}
// 如果当前Cell的Type为STRIN
case Cell.CELL_TYPE_STRING:
// 取得当前的Cell字符串
cellvalue = cell.getStringCellValue().replaceAll("'", "''");
break;
case Cell.CELL_TYPE_BLANK:
cellvalue = " ";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellvalue = cell.getBooleanCellValue()+" ";
break;
case Cell.CELL_TYPE_FORMULA:
cellvalue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_ERROR:
cellvalue = " ";
break;
// 默认的Cell值
default:{
cellvalue = "未知类型";
}
}
} else {
cellvalue = "";
}
return cellvalue;
}
public static void main(String[] args) {
new Thread(new Runnable(){
public void run(){
ExcelToTxt.excelToTxt(new File("F:/test/01-标准分期合同.xlsx"), new File("F:/test/01-标准分期合同.txt"), 1, 6, ",");
}
}).start();
new Thread(new Runnable(){
public void run(){
ExcelToTxt.excelToTxt(new File("F:/test/03-实际还款.xlsx"), new File("F:/test/03-实际还款.txt"), 1,5, ",");
}
}).start();
new Thread(new Runnable(){
public void run(){
ExcelToTxt.excelToTxt(new File("F:/test/02-还款计划.xlsx"), new File("F:/test/02-还款计划.txt"), 1, 6, ",");
}
}).start();
}
}