java实现导出excel事例

public class ExportExcel {
    /**
     * 向excel中写入数据 excel格式为 xlsx
     *
     * @param fileUrl    路径
     * @param sheetName  sheet名称
     * @param dataList   写入的数据集合
     * @param cellTitles 表头
     * @throws FileNotFoundException
     */
    public synchronized static void writeXlsx(String fileUrl, String sheetName, List<Object[]> dataList, String[]
            cellTitles) throws FileNotFoundException {
        File file = new File(fileUrl.substring(0,fileUrl.lastIndexOf("\\")));
        if (!file.exists()) {
            try {
                file.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        FileOutputStream outputStream = new FileOutputStream(fileUrl, true);
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFRow row = null;
        XSSFSheet sheet = wb.createSheet(sheetName);
        try {
            row = sheet.createRow(0);
            // 创建表头
            for (int j = 0; j < cellTitles.length; j++) {
                XSSFCell cell = row.createCell(j);
                cell.setCellValue(cellTitles[j]);
            }
            for (int i = 0; i < dataList.size(); i++) {
                row = sheet.createRow(i + 1);
                Object[] str = dataList.get(i);
                /**
                 * 循环将数据写入excel
                 */
                writeContent(row, str);
            }
            wb.write(outputStream);
            wb.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 逐行写入
     *
     * @param row
     * @param objects
     */
    private synchronized static void writeContent(XSSFRow row, Object[] objects) {
        if (objects.length > 0) {
            for (int i = 0; i < objects.length; i++) {
                XSSFCell XSSFCell = row.createCell(i);
                XSSFCell.setCellValue(objects[i] == null ? "" : objects[i].toString());
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值