javaEE写入数据到预先设置好的excel模板以生成报表
答案:1 悬赏:40 手机版
解决时间 2021-02-03 21:16
- 提问者网友:谁的错
- 2021-02-03 13:45
项目中需要将页面中的数据保存为excel进行报表打印,不知道怎么用poi对excel模板进行写入数据,求大神
最佳答案
- 五星知识达人网友:廢物販賣機
- 2021-02-03 14:13
试试把要替换的 写成特殊格式,如{0},{1}类似,代码里把这些替换掉。
参考:
private static void writeExcel() {
File file = new File(BASE_DIR,"test.xls");
File outFile = new File(BASE_DIR,"test_out.xls");
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(file);
Workbook workbook = new HSSFWorkbook(in);
Sheet sheet = workbook.getSheetAt(0);
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
for(int i=firstRowNum; i<=lastRowNum; i++) {
Row row = sheet.getRow(i);
short firstCellNum = row.getFirstCellNum();
short lastCellNum = row.getLastCellNum();
for(int j = firstCellNum; j<=lastCellNum; j++) {
Cell cell = row.getCell(j);
if(cell != null) {
if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
String value = cell.getStringCellValue() == null ? "" : cell.getStringCellValue();
if("{0}".equals(value.trim())) {
cell.setCellValue("嘿嘿在找到了");
} else if("{1}".equals(value.trim())) {
cell.setCellValue("嗯 好");
}
}
}
}
}
out = new FileOutputStream(outFile);
workbook.write(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
参考:
private static void writeExcel() {
File file = new File(BASE_DIR,"test.xls");
File outFile = new File(BASE_DIR,"test_out.xls");
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(file);
Workbook workbook = new HSSFWorkbook(in);
Sheet sheet = workbook.getSheetAt(0);
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
for(int i=firstRowNum; i<=lastRowNum; i++) {
Row row = sheet.getRow(i);
short firstCellNum = row.getFirstCellNum();
short lastCellNum = row.getLastCellNum();
for(int j = firstCellNum; j<=lastCellNum; j++) {
Cell cell = row.getCell(j);
if(cell != null) {
if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
String value = cell.getStringCellValue() == null ? "" : cell.getStringCellValue();
if("{0}".equals(value.trim())) {
cell.setCellValue("嘿嘿在找到了");
} else if("{1}".equals(value.trim())) {
cell.setCellValue("嗯 好");
}
}
}
}
}
out = new FileOutputStream(outFile);
workbook.write(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯