最近业务场景导出有这个需求,借鉴网上的一些,改成了自己项目中使用的方法
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @author cq
* @date 2020/10/19 10:10
*/
@Slf4j
public class EslConvertToCsv {
public static String csvSeparator = ",";
// TODO: 2020/11/5 可以优化 表头多少行关系...
public static int tableCol = 16;
public static byte[] toCsv(byte[] oldXlsx) throws Exception {
XSSFWorkbook sheets = new XSSFWorkbook(new ByteArrayInputStream(oldXlsx));
StringBuilder result = new StringBuilder();
sheets.forEach(sheet -> sheet.rowIterator().forEachRemaining(row -> {
for (int i = 0; i < tableCol; i++) {
Cell cell = row.getCell(i);
if (row.getCell(i) == null) {
break;
}
result.append(getValue(cell)).append(csvSeparator);
}
if (result.length() > 0)
result.delete(result.length() - 1, result.length());
result.append("\n");
}));
return result.toString().getBytes();
}
public static Object getValue(Cell cell) {
if (cell == null) return "";
CellType cellType = cell.getCellType();
switch (cellType) {
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return cell.getBooleanCellValue();
case FORMULA:
return cell.getCellFormula();
case NUMERIC:
return cell.getNumericCellValue();
case ERROR:
case _NONE:
case BLANK:
default:
return "";
}
}
public static File toConvertCsv(String filePath) {
FileOutputStream fos = null;
BufferedInputStream bis = null;
String newPath;
File file = null;
try {
//旧文件路径
String oldFile = filePath;