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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值