前几天,我在用Java给excel里写数据时,发现只能写最后一个数据,经过很久的思考与调试,最终终于知道了问题的所在。
先来看一下出错的代码:
public static void xlsOutput(int rows,int columns,String str,String outputUrl) {
// rows是要写的行数
//columns是要写的列数
//str是要写的数据
//outputUrl是要写的路径
try {
FileOutputStream fop=new FileOutputStream(outputUrl);
HSSFWorkbook wb =new HSSFWorkbook();
Sheet sheet=wb.createSheet();
Row row=sheet.createRow(rows);
row.createCell(columns).setCellValue(str);
wb.write(fop);
fop.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class MyTest3 {
public static void main(String[] args) {
String outputUrl="C:\\Users\\陈庚\\Desktop\\excel表格\\ranking.xls";
XLS.xlsOutput(0,0,"1000",outputUrl);
XLS.xlsOutput(1,0,"1000",outputUrl);
XLS.xlsOutput(2,0,"1000",outputUrl);
XLS.xlsOutput(3,0,"1000",outputUrl);
}
}
这是之前的结果,这里就出错在我们每次写数据时就会使用new HSSFWorkbook()新创建一个工作簿,然后在新的工作簿里写数据,最后当然只保留最后一次写的数据,因为前面的都被覆盖了。
怎么去解决这个问题呢?我们应该利用读的方式读取到行,这样我们每次根据路径读的时候,就读的是一个工作簿了,利用读的方式拿到行,然后我们在行对应的列去写东西即可,这样就不会出错。
看一下源代码:
public static void xlsOutput(int rows, int columns, String str, String outputUrl) throws Exception {
File file = new File(outputUrl);
Workbook wb;
Sheet sheet;
Row row;
if (file.exists()) {
FileInputStream fip = new FileInputStream(outputUrl);
wb = WorkbookFactory.create(fip);
sheet = wb.getSheetAt(0);
if(rows>sheet.getLastRowNum()){
row = sheet.createRow(rows);
}else {
row = sheet.getRow(rows);
}
fip.close();
} else {
wb = new HSSFWorkbook();
sheet = wb.createSheet();
row = sheet.createRow(rows);
}
HSSFCell cell = (HSSFCell) row.createCell(columns);
cell.setCellType(CellType.STRING);
cell.setCellValue(str);
FileOutputStream fop = new FileOutputStream(outputUrl);
wb.write(fop);
fop.close();
}
我们测试一下:
这样的结果就正确了!