excel文件转PDF或者CSV文件实现

最近业务场景导出有这个需求,借鉴网上的一些,改成了自己项目中使用的方法

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;
            
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值