1. 程式人生 > >POI匯出Excel設定單元格格式

POI匯出Excel設定單元格格式

使用Apache的POI相關API匯出Excel設定單元格格式

栗子,一下各個程式碼之間的變數是通用的,要是在某個程式碼塊中找不到某個變數,則可以向上找尋

準備工作

InputStream = template//檔案輸入流
XSSFWorkbook wb = new XSSFWorkbook(template);
Sheet sheet = wb.getSheetAt(0);

設定單元格格式

XSSFCellStyle cellStyle = wb.createCellStyle();//初始化單元格格式物件
cellStyle.setAlignment(CellStyle.ALIGN_GENERAL);//設定水平對齊方式,有多種對齊方式,如果你稍微瞭解一點英文也能知道:Alignment(水平)、ALIGN_LEFT(左對齊)
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//設定垂直對齊方式,Vertical(垂直)
XSSFDataFormat dataFormat = wb.createDataFormat();//建立格式化物件
cellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));//設定數值型別格式為保留兩位小數
cellStyle.setFillBackgroundColor(IndexedColors.PINK.getIndex());;//設定單元格背景色為騷粉
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//改用指定模式填充單元格顏色(主要用於使你設定的顏色生效以及生效方式)
cellStyle.setWrapText(true);//開啟自動換行
Row excelRow = sheet.createRow(0);//建立單元行,索引從0開始
excelRow.setHeightInPoints(30);//設定行高
sheet.setColumnWidth(i, 256 * 15);//設定某列的列寬,列號為“i”
Cell cell = excelRow.createCell(0);//建立單元格,索引從0開始
cell.setCellStyle(cellStyle);// 設定單元格格式

建立各種型別單元格

        // 建立數字型別的單元格
        Cell cell = row.createCell((short)0);
        cell.setCellValue(1);
        row.createCell(1).setCellValue(1.2);
        //建立單元格並接設定值為簡單字串
        row.createCell(2).setCellValue("This is a string cell");
        //建立單元格並接設定值為富文字
        RichTextString str = creationHelper.createRichTextString("Apache");
        Font font = wb.createFont();
        font.setItalic(true);
        font.setUnderline(Font.U_SINGLE);
        str.applyFont(font);
        row.createCell(3).setCellValue(str);

        //建立boolean型別的單元格
        row.createCell(4).setCellValue(true);
        //建立單元格,當前單元的值是通過公式得到的 formula
        row.createCell(5).setCellFormula("SUM(A1:B1)");
        //建立日期型別的單元格並接進行格式化
        CellStyle style = wb.createCellStyle();
        style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
        cell = row.createCell(6);
        cell.setCellValue(new Date());
        cell.setCellStyle(style);
        //建立超連結型別的單元格
        cell.setCellFormula("HYPERLINK(\"http://baidu.com\",\"baidu\")");

建立單元格註釋

CreationHelper factory = wb.getCreationHelper(); 
Cell cell = sheet.createRow(1).createCell(1);//建立第二行第二列的單元格
Drawing drawing = sheet.createDrawingPatriarch();  //建立頂層DrawingPatriarch,用於新增圖形或圖表(通常會覆蓋原有效果)
ClientAnchor anchor = factory.createClientAnchor();  //建立ClientAnchor,使用此物件將工程圖物件放置在工作表中
Comment comment = drawing.createCellComment(anchor);  //建立註釋
RichTextString text = creationHelper.createRichTextString("flydoging's demo");
Font font = wb.createFont();  //建立字型用於設定註釋字型格式
font.setFontName("Arial");  
font.setFontHeightInPoints((short)14);  
font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
font.setColor(IndexedColors.RED.getIndex());  //設定紅色字型
text.applyFont(font); 
comment.setString(text);//設定註釋體
comment.setAuthor("flydoging");//設定作者
cell.setCellComment(comment); 

CreationHelper是個啥,官方文件
An object that handles instantiating concrete classes of the various instances one needs for HSSF and XSSF. Works around a limitation in Java where we cannot have static methods on interfaces or abstract classes. This allows you to get the appropriate class for a given interface, without you having to worry about if you’re dealing with HSSF or XSSF.
英文不太好,大概意思是說:你可以使用CreationHelper的建立各種用於HSSF、XSSF例項化的物件,通過它的API也可以發現:建立富文字、超連結等等。其實你通過上邊wb建立的是HSSFCreationHelper, SXSSFCreationHelper, XSSFCreationHelper三個其中之一,具體是哪個取決於你使用的WorkBook。

獲取文件的嵌入檔案

    public static void main(String[] args) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook(args[0]);
        for (PackagePart pPart : workbook.getAllEmbedds()) {
            String contentType = pPart.getContentType();
            // Excel Workbook - either binary or OpenXML
            if (contentType.equals("application/vnd.ms-excel")) {//offic 2003 excel
                HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
            }
            // Excel Workbook - OpenXML file format
            else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {//offic 2007 excel
                XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());
            }
            // Word Document - binary (OLE2CDF) file format
            else if (contentType.equals("application/msword")) {//offic 2003 word
                HWPFDocument document = new HWPFDocument(pPart.getInputStream());
            }
            // Word Document - OpenXML file format
            else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
                XWPFDocument document = new XWPFDocument(pPart.getInputStream());
            }
            // PowerPoint Document - binary file format
            else if (contentType.equals("application/vnd.ms-powerpoint")) {
                HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream());
            }
            // PowerPoint Document - OpenXML file format
            else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
                OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
                XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);
            }
            // Any other type of embedded object.
            else {
                System.out.println("Unknown Embedded Document: " + contentType);
                InputStream inputStream = pPart.getInputStream();
            }
        }
    }