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());
            }
        }
    }
}

你可能感兴趣的:(java实现导出excel事例)