java POI创建Excel文件及Sheet

来源:互联网 发布:mac给iphone充电闪跳 编辑:程序博客网 时间:2024/05/17 01:19

一、代码

   //Workbook wb = new XSSFWorkbook();    //FileOutputStream fileOut = new FileOutputStream("E:\\standarcode\\workbook.xlsx");Workbook wb = new HSSFWorkbook();    FileOutputStream fileOut = new FileOutputStream("E:\\standarcode\\workbook.xls");    Sheet sheet1 =  wb.createSheet("new sheet");    Sheet sheet2 =  wb.createSheet("second sheet");        // Note that sheet name is Excel must not exceed 31 characters    // and must not contain any of the any of the following characters:    // 0x0000    // 0x0003    // colon (:)    // backslash (\)    // asterisk (*)    // question mark (?)    // forward slash (/)    // opening square bracket ([)    // closing square bracket (])    // You can use org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}    // for a safe way to create valid names, this utility replaces invalid characters with a space (' ')    String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]"); // returns " O'Brien's sales   "    Sheet sheet3 =  wb.createSheet(safeName);    wb.write(fileOut);    fileOut.close();

二、注意点

1、sheet的名字的长度不能超过31个字符,若是超过的话,会自动截取前31个字符;
2、sheet的名字不能包含如下字符串:
// 0x0000
    // 0x0003
    // colon (:)
    // backslash (\)
    // asterisk (*)
    // question mark (?)
    // forward slash (/)
    // opening square bracket ([)
    // closing square bracket (])
若是包含的话,会报错。但有一个解决此问题的方法,就是调用org.apache.poi.ss.util.WorkbookUtil的createSafeSheetName(String nameProposal)方法来创建sheet name,若是有如上特殊字符,它会自动用空字符来替换掉,自动过滤。


0 0
原创粉丝点击