java通過poi包操作excel

不要把問題想得太複雜,目前沒有什麼具體應用,就先看了一點簡單的操作。

往excel裏面寫內容:

public static void main(String[] args) {

            try {
                HSSFWorkbook workbook= new HSSFWorkbook();
                HSSFSheet sheet= workbook.createSheet("test");
                HSSFRow row = sheet.createRow(2);
                HSSFCell cell= row.createCell(2);
                cell.setCellValue("test1");
                FileOutputStream os= new FileOutputStream("/Users/username/aaa.xls");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("ok");
    }
讀取excel裏面的內容:

public static void main(String[] args) {
        try {
            FileInputStream file= new FileInputStream("/Users/username/aaa.xls");
            POIFSFileSystem ts= new POIFSFileSystem(file);
            HSSFWorkbook wb=new HSSFWorkbook(ts);
            HSSFSheet sh= wb.getSheetAt(0);
            HSSFRow ro=null;
            for (int i = 0; sh.getRow(i)!=null; i++) {
                ro=sh.getRow(i);
                for (int j = 0; ro.getCell(j)!=null; j++) {
                    System.out.print(ro.getCell(j)+"#");
                }
                System.out.println();
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e){

        }
        System.out.println("OK");
    }
有個稍微複雜一點的例子:
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";

/**
 * 判斷Excel的版本,獲取Workbook
 * @param in
 * @param filename
 * @return
 * @throws IOException
 */
public static Workbook getWorkbok(InputStream in,File file) throws IOException{
    Workbook wb = null;
    if(file.getName().endsWith(EXCEL_XLS)){  //Excel 2003
        wb = new HSSFWorkbook(in);
    }else if(file.getName().endsWith(EXCEL_XLSX)){  // Excel 2007/2010
        wb = new XSSFWorkbook(in);
    }
    return wb;
}

/**
 * 判斷文件是否是excel
 * @throws Exception
 */
public static void checkExcelVaild(File file) throws Exception{
    if(!file.exists()){
        throw new Exception("文件不存在");
    }
    if(!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))){
        throw new Exception("文件不是Excel");
    }
}

/**
 * 讀取Excel測試,兼容 Excel 2003/2007/2010
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/Users/username/InsertSql.txt")));
    try {
        // 同時支持Excel 2003、2007
        File excelFile = new File("/Users/username/aaa.xls"); // 創建文件對象
        FileInputStream is = new FileInputStream(excelFile); // 文件流
        checkExcelVaild(excelFile);
        Workbook workbook = getWorkbok(is,excelFile);
        //Workbook workbook = WorkbookFactory.create(is); // 這種方式 Excel2003/2007/2010都是可以處理的

        int sheetCount = workbook.getNumberOfSheets(); // Sheet的數量
        /**
         * 設置當前excel中sheet的下標:0開始
         */
        Sheet sheet = workbook.getSheetAt(0);   // 遍歷第一個Sheet

        // 爲跳過第一行目錄設置count
        int count = 0;

        for (Row row : sheet) {
            // 跳過第一行的目錄
            if(count == 0){
                count++;
                continue;
            }
            // 如果當前行沒有數據,跳出循環
            if(row.getCell(0).toString().equals("")){
                return ;
            }
            String rowValue = "";
            for (Cell cell : row) {
                if(cell.toString() == null){
                    continue;
                }
                int cellType = cell.getCellType();
                String cellValue = "";
                switch (cellType) {
                    case Cell.CELL_TYPE_STRING:     // 文本
                        cellValue = cell.getRichStringCellValue().getString() + "#";
                        break;
                    case Cell.CELL_TYPE_NUMERIC:    // 數字、日期
                        if (DateUtil.isCellDateFormatted(cell)) {
                            cellValue = fmt.format(cell.getDateCellValue()) + "#";
                        } else {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            cellValue = String.valueOf(cell.getRichStringCellValue().getString()) + "#";
                        }
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:    // 布爾型
                        cellValue = String.valueOf(cell.getBooleanCellValue()) + "#";
                        break;
                    case Cell.CELL_TYPE_BLANK: // 空白
                        cellValue = cell.getStringCellValue() + "#";
                        break;
                    case Cell.CELL_TYPE_ERROR: // 錯誤
                        cellValue = "錯誤#";
                        break;
                    case Cell.CELL_TYPE_FORMULA:    // 公式
                        // 得到對應單元格的公式
                        //cellValue = cell.getCellFormula() + "#";
                        // 得到對應單元格的字符串
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cellValue = String.valueOf(cell.getRichStringCellValue().getString()) + "#";
                        break;
                    default:
                        cellValue = "#";
                }
                //System.out.print(cellValue);
                rowValue += cellValue;
            }
            writeSql(rowValue,bw);
            System.out.println(rowValue);
            System.out.println();
        }
        bw.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally{
        bw.close();
    }
}


public static void writeSql(String rowValue,BufferedWriter bw) throws IOException{
    String[] sqlValue = rowValue.split("#");
    String sql = "";
    sql="INSERT INTO table_name (列名1) VALUES("+ sqlValue[0].trim() + ");"+"\n";
    System.out.print(sql);
    try {
        bw.write(sql);
        bw.newLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

總之就是,通過Row讀取行,通過cell讀取行中的單元格,進行相應的讀寫操作。

有個問題,爲什麼在excel文件中新建sheet時,會覆蓋(刪除)原來所有的sheet?

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