日期:2014-05-17  浏览次数:20776 次

Apache POI 官方文档解析和趣谈

我希望看到这篇文章大家不要转载

?

在这里我想说明一下,我接触POI也是不太时间,有句话大家都会说,“如果有什么不对的地方,希望大家包涵”,哈哈

我这里也引用一下,如果有错误的地方,希望大家指出来,我非常高兴

?

我这篇文章不想长篇大论的讲POI是什么,题目为趣谈,那么当然是开开心心的学习一门新技术,哈哈,好吧,废话就不说了,现在开始

?

Apache POI - the Java API for Microsoft Documents

官方的大题目,哇,好大,哈哈,很明显POI是什么 就是java API ,什么API,是为了解析微软文档文件的,哈哈我说了一堆废话,哈哈,简直就是在翻译吗。。。翻译也罢,反正POI就是这个意思

?

?

官网大篇幅的讲述POI是做什么的,这里我不想当interpreter,所以这里就不翻译了,我建议大家读读,为了更加了解POI,这里我提供链接

?

官网:?http://poi.apache.org/index.html

?

至于下载吗,哈哈,我想做技术的,不用我叫怎么下载吧,你们懂的

?

既然POI是解析MD(Microsoft Document),那么我们对MD分别分析

?

Excel?

?

我把官网给的图图做了处理,让大家看的更加清晰:


?

上面的图已经很清晰的说明Excel2003和Excel2003的基本区别和相同点,POI对Excel2010其实和2007出不多,但有的时候会出现bug。我没有做尝试,这里暂不说明

?

基本操作:

?

1.创建Excel文件

?

?

Workbook wb = new HSSFWorkbook();
    FileOutputStream fileOut = new FileOutputStream("excel.xls");
    wb.write(fileOut);
    fileOut.close();

?

 Workbook wb = new XSSFWorkbook();
    FileOutputStream fileOut = new FileOutputStream("excel.xlsx");
    wb.write(fileOut);
    fileOut.close();

?

noite: 第一HSSF只能创建后缀名为.xls文件,XSSF只能创建xlsx文件 互换的,生成的excel打不开

?

2.创建sheet

?

?

   Workbook wb = new HSSFWorkbook();  // or new XSSFWorkbook();
    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);

    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();
?

?

这是官网给力例子,我这里直接写出,嘿嘿,趣谈来了,要注意哦名字就有限制的,所以最好用createSafeSheetName

?

3.创建cell

?

?

 Workbook wb = new HSSFWorkbook();
    //Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("new sheet");

    // Create a row and put some cells in it. Rows are 0 based.
    Row row = sheet.createRow((short)0);
    // Create a cell and put a value in it.
    Cell cell = row.createCell(0);
    cell.setCellValue(1);

    // Or do it on one line.
    row.createCell(1).setCellValue(1.2);
    row.createCell(2).setCellValue(
         createHelper.createRichTextString("This is a string"));
    row.createCell(3).setCellValue(true);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

?