POI創建和讀取excel文件

  1. Poi創建excel文件

    所需jar:poi-3.11-20141221.jar  commons-io-2.2.jar

    public class PoiExpExcel {

        /**
         * POI生成Excel文件
         */
        public static void main(String[] args) {

            String[] title = {"id","name","sex"};
            
            //新建工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            //新建sheet
            HSSFSheet sheet = workbook.createSheet();
            //創建第一行
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = null;
            //創建第一行id,name,sex
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            //添加數據
            for (int i = 1; i <= 10; i++) {
                HSSFRow nextrow = sheet.createRow(i);
                HSSFCell cell2 = nextrow.createCell(0);
                cell2.setCellValue("a" + i);
                cell2 = nextrow.createCell(1);
                cell2.setCellValue("user" + i);
                cell2 = nextrow.createCell(2);
                cell2.setCellValue("男");
            }
            //創建excel
            File file = new File("e:/poi_test.xls");
            try {
                file.createNewFile();
                //存入excel
                FileOutputStream stream = FileUtils.openOutputStream(file);
                workbook.write(stream);
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }

    }

    2.POI讀取excel裏的內容

    public class PoiReadExcel {

        /**
         * poi讀取excel
         */
        public static void main(String[] args) {

            
            File file = new File("e:/poi_test.xls");
            try {
                HSSFWorkbook workbook =
                    new HSSFWorkbook(FileUtils.openInputStream(file));
                //獲取第一個工作表workbook.getSheet("Sheet0");
    //            HSSFSheet sheet = workbook.getSheet("Sheet0");
                //獲取默認的第一個sheet
                HSSFSheet sheet = workbook.getSheetAt(0);
                int firstRowNum = 0;
                //獲取sheet裏最後一行行號
                int lastRowNum = sheet.getLastRowNum();
                for (int i = firstRowNum; i <=lastRowNum; i++) {
                    HSSFRow row = sheet.getRow(i);
                    //獲取當前行最後一個單元格號
                    int lastCellNum = row.getLastCellNum();
                    for (int j = 0; j < lastCellNum; j++) {
                        HSSFCell cell = row.getCell(j);
                        String value = cell.getStringCellValue();
                        System.out.print(value + "  ");
                    }
                    System.out.println();
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            
            
        }

    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章