java替换Excel中指定字符串(poi)

2025-04-22 17:58:46

1、//模板路径String modelPath="D:\Excel.xls"//sheet的名字StringsheetName="sheet1";获取Ex艘早祓胂cel模板对象try { File file = new File(modelPath); if(!file.exists()){ System.out.println("模板文件:"+modelPath+"不存在!"); } fs = new POIFSFileSystem(new FileInputStream(file)); wb = new HSSFWorkbook(fs); sheet = wb.getSheet(sheetName); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

2、//从heet中获取行数 int rowNum = sheet.getLastRowNum();

3、//获取行里面的总列数row = sheet.getRow(i); //i:第I行 // 获取行里面的总列数 int columnNum = 0; if(row!=null){ columnNum = row.getPhysicalNumberOfCells(); }

4、//获取单元格的值HSSFCell cell = sheet.getRow(i).getCell(j); //第i行,第j列 String cellValue = cell.getStringCellValue();

5、//替换数据 本人的数据存放在Map中for (Entry<String, Object> entry : param.entrySet()) { String key = entry.getKey(); if(key.equals(cellValue)){ String value = entry.getValue().toString(); setCellStrValue(i, j, value);//设置第i行,第j列的值为Value } }

6、完整代码: /** * 替换Excel模板中的数据 * @param sheetName Sheet名字 * @param modelPath 模板路径 * @param param 需要替换的数据 * @return * @author 刘泽中 * @Date: 2015年12月11日 */ public HSSFWorkbook replaceExcel(String sheetName,String modelPath,Map<String, Object> param){ //获取所读取excel模板的对象 try { File file = new File(modelPath); if(!file.exists()){ System.out.println("模板文件:"+modelPath+"不存在!"); } fs = new POIFSFileSystem(new FileInputStream(file)); wb = new HSSFWorkbook(fs); sheet = wb.getSheet(sheetName); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } replaceExcelDate(param); return wb; } /** * 根据 Map中的数据替换Excel模板中指定数据 * @param param * @author 刘泽中 * @Date: 2015年12月11日 */ public void replaceExcelDate(Map<String, Object> param){ // 获取行数 int rowNum = sheet.getLastRowNum(); for (int i = 0; i < rowNum; i++) { row = sheet.getRow(i); // 获取行里面的总列数 int columnNum = 0; if(row!=null){ columnNum = row.getPhysicalNumberOfCells(); } for (int j = 0; j < columnNum; j++) { HSSFCell cell = sheet.getRow(i).getCell(j); String cellValue = cell.getStringCellValue(); for (Entry<String, Object> entry : param.entrySet()) { String key = entry.getKey(); if(key.equals(cellValue)){ String value = entry.getValue().toString(); setCellStrValue(i, j, value); } } } } } /** * 设置字符串类型的数据 * @param rowIndex--行值 从0开始 * @param cellnum--列值 从0开始 * @param value--字符串类型的数据 * * @author 刘泽中 * @Date: 2015年12月11日 */ public void setCellStrValue(int rowIndex, int cellnum, String value) { HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum); cell.setCellValue(value); }

java替换Excel中指定字符串(poi)
java替换Excel中指定字符串(poi)
java替换Excel中指定字符串(poi)
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢