POI操作Excel詳解,HSSF和XSSF兩種方式

jopen 10年前發布 | 253K 次閱讀 POI Office文檔處理

HSSF方式:

    package com.tools.poi.lesson1;

import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;  
import java.util.List;  

import org.apache.poi.hssf.usermodel.HSSFCell;  
import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
import org.apache.poi.hssf.usermodel.HSSFRow;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.hssf.util.HSSFColor;  
import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.CellStyle;  

import com.tools.poi.bean.Student;  

public class ExcelUtilWithHSSF {  
    public static void main(String[] args) {  
        try {  
            getExcelAsFile("aaa");  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  


//      try {  
//          CreateExcelDemo1();  
//      } catch (ParseException e) {  
//          e.printStackTrace();  
//      }  


    }  

    /** 
     * 得到Excel,并解析內容 
     * @param file 
     * @throws FileNotFoundException 
     * @throws IOException 
     */  
    public static void getExcelAsFile(String file) throws FileNotFoundException, IOException{  
        //1.得到Excel常用對象  
//      POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/test.xls"));  
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls"));  
        //2.得到Excel工作簿對象  
        HSSFWorkbook wb = new HSSFWorkbook(fs);  
        //3.得到Excel工作表對象  
        HSSFSheet sheet = wb.getSheetAt(0);  
        //總行數  
        int trLength = sheet.getLastRowNum();  
        //4.得到Excel工作表的行  
        HSSFRow row = sheet.getRow(0);  
        //總列數  
        int tdLength = row.getLastCellNum();  
        //5.得到Excel工作表指定行的單元格  
        HSSFCell cell = row.getCell((short)1);  
        //6.得到單元格樣式  
        CellStyle cellStyle = cell.getCellStyle();  
        for(int i=0;i<trLength;i++){  
            //得到Excel工作表的行  
            HSSFRow row1 = sheet.getRow(i);  
            for(int j=0;j<tdLength;j++){  

            //得到Excel工作表指定行的單元格  
            HSSFCell cell1 = row1.getCell(j);  

            /** 
             * 為了處理:Excel異常Cannot get a text value from a numeric cell 
             * 將所有列中的內容都設置成String類型格式 
             */  
            if(cell1!=null){  
                  cell1.setCellType(Cell.CELL_TYPE_STRING);  
             }  

            //獲得每一列中的值  
            System.out.print(cell1.getStringCellValue()+"\t\t\t");  
            }  
            System.out.println();  
        }  
    }  


    /** 
     * 創建Excel,并寫入內容 
     */  
    public static void CreateExcel(){  

        //1.創建Excel工作薄對象  
        HSSFWorkbook wb = new HSSFWorkbook();  
        //2.創建Excel工作表對象       
        HSSFSheet sheet = wb.createSheet("new Sheet");  
        //3.創建Excel工作表的行     
        HSSFRow row = sheet.createRow(6);  
        //4.創建單元格樣式  
        CellStyle cellStyle =wb.createCellStyle();  
          // 設置這些樣式  
        cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  



        //5.創建Excel工作表指定行的單元格  
        row.createCell(0).setCellStyle(cellStyle);  
        //6.設置Excel工作表的值  
        row.createCell(0).setCellValue("aaaa");  

        row.createCell(1).setCellStyle(cellStyle);  
        row.createCell(1).setCellValue("bbbb");  


        //設置sheet名稱和單元格內容  
        wb.setSheetName(0,"第一張工作表");  
        //設置單元格內容   cell.setCellValue("單元格內容");  

        // 最后一步,將文件存到指定位置  
                try  
                {  
                    FileOutputStream fout = new FileOutputStream("E:/students.xls");  
                    wb.write(fout);  
                    fout.close();  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();  
                }  
    }  

    /** 
     * 創建Excel的實例 
     * @throws ParseException  
     */  
    public static void CreateExcelDemo1() throws ParseException{  
        List list = new ArrayList();  
        SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");  
        Student user1 = new Student(1, "張三", 16,true, df.parse("1997-03-12"));  
        Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12"));  
        Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12"));  
        list.add(user1);  
        list.add(user2);  
        list.add(user3);  


        // 第一步,創建一個webbook,對應一個Excel文件  
                HSSFWorkbook wb = new HSSFWorkbook();  
                // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet  
                HSSFSheet sheet = wb.createSheet("學生表一");  
                // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short  
                HSSFRow row = sheet.createRow((int) 0);  
                // 第四步,創建單元格,并設置值表頭 設置表頭居中  
                HSSFCellStyle style = wb.createCellStyle();  
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式  

                HSSFCell cell = row.createCell((short) 0);  
                cell.setCellValue("學號");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 1);  
                cell.setCellValue("姓名");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 2);  
                cell.setCellValue("年齡");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 3);  
                cell.setCellValue("性別");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 4);  
                cell.setCellValue("生日");  
                cell.setCellStyle(style);  

                // 第五步,寫入實體數據 實際應用中這些數據從數據庫得到,  

                for (int i = 0; i < list.size(); i++)  
                {  
                    row = sheet.createRow((int) i + 1);  
                    Student stu = (Student) list.get(i);  
                    // 第四步,創建單元格,并設置值  
                    row.createCell((short) 0).setCellValue((double) stu.getId());  
                    row.createCell((short) 1).setCellValue(stu.getName());  
                    row.createCell((short) 2).setCellValue((double) stu.getAge());  
                    row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女");  
                    cell = row.createCell((short) 4);  
                    cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu  
                            .getBirthday()));  
                }  
                // 第六步,將文件存到指定位置  
                try  
                {  
                    FileOutputStream fout = new FileOutputStream("E:/students.xls");  
                    wb.write(fout);  
                    fout.close();  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();  
                }  



    }  
}  </pre>XSSF方式:<pre class="brush:java; toolbar: true; auto-links: false;">    package com.tools.poi.lesson1;  

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;  
import java.util.List;  

import org.apache.poi.hssf.usermodel.HSSFCell;  
import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
import org.apache.poi.hssf.usermodel.HSSFRow;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.hssf.util.HSSFColor;  
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.CellStyle;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.ss.usermodel.Sheet;  
import org.apache.poi.ss.usermodel.Workbook;  
import org.apache.poi.ss.usermodel.WorkbookFactory;  
import org.apache.poi.ss.util.WorkbookUtil;  

import com.tools.poi.bean.Student;  

public class ExcelUtilWithXSSF {  
    public static void main(String[] args) {  
        try {  
            getExcelAsFile("d:/FTP/系統報表.xls");  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (InvalidFormatException e) {  
            e.printStackTrace();  
        }  


//      try {  
//          CreateExcelDemo1();  
//      } catch (ParseException e) {  
//          e.printStackTrace();  
//      }  


    }  

    /** 
     * 得到Excel,并解析內容  對2007及以上版本 使用XSSF解析 
     * @param file 
     * @throws FileNotFoundException 
     * @throws IOException 
     * @throws InvalidFormatException  
     */  
    public static void getExcelAsFile(String file) throws FileNotFoundException, IOException, InvalidFormatException{  
//      //1.得到Excel常用對象  
//      POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls"));  
//      //2.得到Excel工作簿對象  
//      HSSFWorkbook wb = new HSSFWorkbook(fs);  



        InputStream ins = null;     
        Workbook wb = null;     
            ins=new FileInputStream(new File(file));     
            //ins= ExcelService.class.getClassLoader().getResourceAsStream(filePath);     
            wb = WorkbookFactory.create(ins);     
            ins.close();     


        //3.得到Excel工作表對象  
        Sheet sheet = wb.getSheetAt(0);  
        //總行數  
        int trLength = sheet.getLastRowNum();  
        //4.得到Excel工作表的行  
        Row row = sheet.getRow(0);  
        //總列數  
        int tdLength = row.getLastCellNum();  
        //5.得到Excel工作表指定行的單元格  
        Cell cell = row.getCell((short)1);  
        //6.得到單元格樣式  
        CellStyle cellStyle = cell.getCellStyle();  

        for(int i=5;i<trLength;i++){  
            //得到Excel工作表的行  
            Row row1 = sheet.getRow(i);  
            for(int j=0;j<tdLength;j++){  
            //得到Excel工作表指定行的單元格  
            Cell cell1 = row1.getCell(j);  
            /** 
             * 為了處理:Excel異常Cannot get a text value from a numeric cell 
             * 將所有列中的內容都設置成String類型格式 
             */  
            if(cell1!=null){  
                  cell1.setCellType(Cell.CELL_TYPE_STRING);  
             }  

            if(j==5&&i<=10){  
                cell1.setCellValue("1000");  
            }  

            //獲得每一列中的值  
            System.out.print(cell1+"                   ");  
            }  
            System.out.println();  
        }  

        //將修改后的數據保存  
        OutputStream out = new FileOutputStream(file);  
                wb.write(out);  
    }  


    /** 
     * 創建Excel,并寫入內容 
     */  
    public static void CreateExcel(){  

        //1.創建Excel工作薄對象  
        HSSFWorkbook wb = new HSSFWorkbook();  
        //2.創建Excel工作表對象       
        HSSFSheet sheet = wb.createSheet("new Sheet");  
        //3.創建Excel工作表的行     
        HSSFRow row = sheet.createRow(6);  
        //4.創建單元格樣式  
        CellStyle cellStyle =wb.createCellStyle();  
          // 設置這些樣式  
        cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  



        //5.創建Excel工作表指定行的單元格  
        row.createCell(0).setCellStyle(cellStyle);  
        //6.設置Excel工作表的值  
        row.createCell(0).setCellValue("aaaa");  

        row.createCell(1).setCellStyle(cellStyle);  
        row.createCell(1).setCellValue("bbbb");  


        //設置sheet名稱和單元格內容  
        wb.setSheetName(0,"第一張工作表");  
        //設置單元格內容   cell.setCellValue("單元格內容");  

        // 最后一步,將文件存到指定位置  
                try  
                {  
                    FileOutputStream fout = new FileOutputStream("E:/students.xls");  
                    wb.write(fout);  
                    fout.close();  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();  
                }  
    }  

    /** 
     * 創建Excel的實例 
     * @throws ParseException  
     */  
    public static void CreateExcelDemo1() throws ParseException{  
        List list = new ArrayList();  
        SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");  
        Student user1 = new Student(1, "張三", 16,true, df.parse("1997-03-12"));  
        Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12"));  
        Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12"));  
        list.add(user1);  
        list.add(user2);  
        list.add(user3);  


        // 第一步,創建一個webbook,對應一個Excel文件  
                HSSFWorkbook wb = new HSSFWorkbook();  
                // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet  
                HSSFSheet sheet = wb.createSheet("學生表一");  
                // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short  
                HSSFRow row = sheet.createRow((int) 0);  
                // 第四步,創建單元格,并設置值表頭 設置表頭居中  
                HSSFCellStyle style = wb.createCellStyle();  
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式  

                HSSFCell cell = row.createCell((short) 0);  
                cell.setCellValue("學號");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 1);  
                cell.setCellValue("姓名");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 2);  
                cell.setCellValue("年齡");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 3);  
                cell.setCellValue("性別");  
                cell.setCellStyle(style);  
                cell = row.createCell((short) 4);  
                cell.setCellValue("生日");  
                cell.setCellStyle(style);  

                // 第五步,寫入實體數據 實際應用中這些數據從數據庫得到,  

                for (int i = 0; i < list.size(); i++)  
                {  
                    row = sheet.createRow((int) i + 1);  
                    Student stu = (Student) list.get(i);  
                    // 第四步,創建單元格,并設置值  
                    row.createCell((short) 0).setCellValue((double) stu.getId());  
                    row.createCell((short) 1).setCellValue(stu.getName());  
                    row.createCell((short) 2).setCellValue((double) stu.getAge());  
                    row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女");  
                    cell = row.createCell((short) 4);  
                    cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu  
                            .getBirthday()));  
                }  
                // 第六步,將文件存到指定位置  
                try  
                {  
                    FileOutputStream fout = new FileOutputStream("E:/students.xls");  
                    wb.write(fout);  
                    fout.close();  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();  
                }  



    }  
}  </pre> <p>注意:</p>

修改Excel中的某個內容:

 
    cell1.setCellValue("1000");  

保存修改后的Excel文件:

OutputStream out = new FileOutputStream(file);  
wb.write(out);  
</div> </div> 來自:http://blog.csdn.net/he90227/article/details/37563497

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!