java excel 사례 내보내기

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

좋은 웹페이지 즐겨찾기