Jxl創建和讀取excel文件

  1. 利用jxl創建excel文件

    所需jar包 jxl.jar

    public class JxlExpExcel {

        /*
         * 使用jxl生成excel
         */
        public static void main(String[] args) {
            String[] title = {"id","name","sex"};
            //創建Excel文件
            File file = new File("e:/jxl_test.xls");
            try {
                file.createNewFile();
                //創建工作簿
                WritableWorkbook workbook = Workbook.createWorkbook(file);
                //創建sheet
                WritableSheet sheet = workbook.createSheet("sheet1", 0);
                Label label = null;
                //往sheet裏寫入數據
                //第一行設置列名
                for (int i = 0; i < title.length; i++) {
                    label = new Label(i,0,title[i]);
                    sheet.addCell(label);    
                }
                //追加數據
                for (int i = 1; i < 10; i++) {
                    label = new Label(0,i,"a" + i);
                    sheet.addCell(label);
                    label = new Label(1,i,"user" + i);
                    sheet.addCell(label);
                    label = new Label(2,i,"男");
                    sheet.addCell(label);
                }
                //寫入數據
                workbook.write();
                workbook.close();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

2,讀取excel裏的數據打印到控制檯

    public class JxlReadExcel {

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

        try {
            //新建workbook
            Workbook workbook = Workbook.getWorkbook(new File("e:/jxl_test.xls"));
            //獲取sheet
            Sheet sheet = workbook.getSheet(0);
            //獲取單元格里的數據
            for (int i = 0; i < sheet.getRows(); i++) {
                for (int j = 0; j < sheet.getColumns(); j++) {
                    Cell cell = sheet.getCell(j,i);
                    System.out.print(cell.getContents() + "  ");
                }
                System.out.println();
            }
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
        
    }

}



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