Apache POI HSSF, XSSF and EXCEL


Want to use HSSF and XSSF read and write spreadsheets in a hurry?
HSSF is for less than 2007 year Excel, XSSF is for more than 2007 year Excel.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;


public class testHSSF {   

    public static void main(String[] args) throws IOException {  

        Workbook wb = new HSSFWorkbook();

 CreationHelper helper = wb.getCreationHelper(); 

//Create Sheet  

Sheet sheet01 = wb.createSheet("HSSF_Sheet_01");

Sheet sheet02 = wb.createSheet("HSSF_Sheet_02");

Row row = null;

Cell cell = null;

  for(int i=0;i<60;i=i+2){

    row = sheet01.createRow(i);
    row.setHeightInPoints(20);//row.setHeight((short)500);//row.setZeroHeight(true);
            for(int j=0;j<25;j++){       
                //set each column size
                sheet01.autoSizeColumn(j+1, true);
                //create style
                CellStyle cellStyle = SummaryHSSF.createStyleCell(wb);
                //get cell of row
                cell = row.createCell(j);
                if(j==0){
 
                    cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                    cellStyle.setFont(createFonts(wb));
                    cell.setCellStyle(cellStyle);                   
                    cell.setCellValue(true);
                }else if(j==1){
                    cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                    cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "#,##0.0000");                  
                    cellStyle.setFont(createFonts(wb));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(new Double(2008.2008));
                }else if(j==2){
                    cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);                    
                    cellStyle.setFont(createFonts(wb));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(helper.createRichTextString("RichString"+i+j));                   
                }else if(j==3){
                    cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                    cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "MM-yyyy-dd");
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(new Date());
                }else if(j==24){
                    cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                    cellStyle.setFont(createFonts(wb));
                    cell.setCellFormula("SUM(E"+(i+1)+":X"+(i+1)+")");                  
                }else{                  
                    cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                    cellStyle = SummaryHSSF.setFillBackgroundColors(cellStyle,IndexedColors.ORANGE.getIndex(),IndexedColors.ORANGE.getIndex(),CellStyle.SOLID_FOREGROUND);
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(1);
                }
            }
        }

        OutputStream os = new FileOutputStream(new File("c://SummaryHSSF.xls"));
        wb.write(os);
        os.close();     
    }
    /**
     * border
     * @param wb
     * @return
     */
    public static CellStyle createStyleCell(Workbook wb){
        CellStyle cellStyle = wb.createCellStyle();
        
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());        
        return cellStyle;
    }
    /**
     * set local
     * CellStyle.ALIGN_CENTER
     * CellStyle.VERTICAL_CENTER
     * @param cellStyle
     * @param halign
     * @param valign
     * @return
     */
    public static CellStyle setCellStyleAlignment(CellStyle cellStyle,short halign,short valign){
        
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        return cellStyle;
    }
    /**
     * cell format
     * 如#,##0.00,m/d/yy(HSSFDataFormat,XSSFDataFormat)
     * @param cellStyle
     * @param fmt
     * @return
     */
    public static CellStyle setCellFormat(CreationHelper helper,CellStyle cellStyle,String fmt){
        
        cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));
        return cellStyle;
    }
    /**
     * beforeground and background colour
     * @param cellStyle
     * @param bg IndexedColors.ORANGE.getIndex();
     * @param fg IndexedColors.ORANGE.getIndex();
     * @param fp CellStyle.SOLID_FOREGROUND
     * @return
     */
    public static CellStyle setFillBackgroundColors(CellStyle cellStyle,short bg,short fg,short fp){
        //cellStyle.setFillBackgroundColor(bg);
        cellStyle.setFillForegroundColor(fg);
        cellStyle.setFillPattern(fp);
        return cellStyle;
    }
    /**
     * set font
     * @param wb
     * @return
     */
    public static Font createFonts(Workbook wb){
        //create Font object
        Font font = wb.createFont();
        //setFontName
        font.setFontName("Calibri");
        
        font.setColor(HSSFColor.BLUE.index);
        
        font.setItalic(true);
        
        font.setFontHeight((short)300);
        return font;
    }
}
//------------------------------
    public class ReadExcel { 
        public static void main(String[] args) throws Exception { 
            InputStream is = new FileInputStream(new File("D://testHSSF.xls")); 

            Workbook wb = WorkbookFactory.create(is); 
            Sheet sheet = wb.getSheetAt(0); 
            // 
            for(Row row : sheet){ 
                for(Cell cell : row){ 
                    
                    switch(cell.getCellType()){//Cell.CELL_TYPE_STRING 
                        case Cell.CELL_TYPE_BOOLEAN: 
                             
                            System.out.print(cell.getBooleanCellValue()+" "); 
                            break; 
                        case Cell.CELL_TYPE_NUMERIC: 
                            
                            if(DateUtil.isCellDateFormatted(cell)){ 
                                 
                                System.out.print(cell.getDateCellValue()+" "); 
                            }else{ 
                                 
                                System.out.print(cell.getNumericCellValue()+" "); 
                            } 
                            break; 
                        case Cell.CELL_TYPE_FORMULA: 
                            //formula 
                            System.out.print(cell.getCellFormula()+" "); 
                            break; 
                        case Cell.CELL_TYPE_STRING: 
                            //get String 
                            System.out.print(cell.getRichStringCellValue().toString()+" "); 
                            break;                   
                    } 
                } 
                System.out.println(""); 
            } 
        } 
    }

At Servlet
  1. // clear response  
  2. response.reset();  
  3. // set header of response 
  4. response.addHeader("Content-Disposition""attachment;filename=excel00.xls");  
  5. // one way
    OutputStream out = new BufferedOutputStream(response.getOutputStream());  response.setContentType("application/octet-stream");  HSSFWorkbook workbook = new HSSFWorkbook();  HSSFSheet sheet = workbook.createSheet("sheet"); 
    ......
    workbook.write(out);
  6. // two way
    WritableWorkbook w = Workbook.createWorkbook(response.getOutputStream());
    WritableSheet s = w.createSheet("Demo", 0);
           
       //..
     w.write();
     w.close();
     
  7. out.flush();  
  8. out.close(); 


Ref: p o i. a p a c h e . o r g / s p r e a d s h e e t / q u i c k - g u i d e . h t m l  
l a n g h u a 9 5 2 7 . i t e y e . c o m / b l o g / 3 8 8 0 0 5

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE