我陷入了僵局。
我将值存储在 ArrayList 中。 每个值都是一个字符串,由分隔符 (##) 分隔的几个其他字符串连接而成。
Eg: ArrayList lst has following 4 values.
- aaa##bbb##ccc##
- d##ee##ffdfg##
- w##xx##zzzzz##
- mmmm##n##ooo##
我正在 for 循环中迭代 for lst.size(),并一次获取每个值。在哪里,我将字符串拆分并将其存储到字符串数组中。
erow = aaa##bbb##ccc##
String[] arry = erow.split("##");
在这个 for 循环中,我使用另一个 for 循环,让 arry.length() 获取每个字符串(如 aaa)并写入它使用 Apache POI 进入 Excel 上的单元格。 最后,我想要aaa在Excel的单元格A1中,bbb在单元格B1中,ccc在单元格C1中,d在单元格 A2 中,依此类推。
我面临的问题是,每次迭代后,前一列(A1 到 A4、B1 到 B4 等)中的值都会被删除。最后,只剩下 C1 到 C4 值。
我使用了 CreateRow 和 CreateCell 方法。 如果我使用 getRow 和 getCell 方法,我将收到 NullPointerException!
如果我使用在 A1 到 C4 单元格中包含一些数据的 Excel,并使用 getRow、getCell 和 setCellValue 方法,一切都会非常顺利。 aaa、bbb 值正在写入相应的单元格。
但每次我都无法使用 Excel 处理现有数据。我想将数据写入新的 Excel 文件。 如果excel没有任何数据,getCell、getRow方法会抛出NPE。
请帮忙..我该如何解决这个问题?
<小时/>主函数()
xlo.createExcel(xlPath, xl_name, tabName,".xls");
for(int s=0;s<vals.size();s++)
{
erow = vals.get(s);
String[] cval = erow.split("###");
for(int c=0; c<cval.length;c++)
{
xlo.writeExcel(xlPath+"/"+xl_name, tabName, s, c, cval[c]);
System.out.println(cval[c]);
}
System.out.println();
}
System.out.println("File created ---> "+xl_name+"\n");
<小时/>
WriteExcel()
public void writeExcel(String xlPath, String xlSheet, int rowNum, int cellNum, String inputString) throws Exception
{
FileInputStream fis = new FileInputStream(xlPath);
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(xlSheet);
Row row = sh.createRow(rowNum);
Cell cell=row.createCell(cellNum);
CellStyle cs = wb.createCellStyle();
//cs.setWrapText(true);
cell.setCellStyle(cs);
cell.setCellValue(inputString);
FileOutputStream fos=new FileOutputStream(xlPath);
wb.write(fos);
wb.close();
fos.close();
}
<小时/>
CreateExcel()
public void createExcel(String path, String fileName, String tabName, String fileExtn) throws Exception
{
Workbook workbook = new XSSFWorkbook();
workbook.createSheet(tabName);
FileOutputStream fileOut;
try
{
fileOut = new FileOutputStream(path+"/"+fileName+fileExtn);
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
catch (Exception e)
{
System.out.println("Excel not created!");
}
}
最佳答案
我之前就必须这样做(但使用 ,
分隔符)。这是 ##
代码的简化版本:
private XSSFWorkbook writeToExcel(LinkedHashMap<Integer, String> formattedReport) {
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
int rowIndex = sheet.getLastRowNum();
Set<Integer> keySet = formattedReport.keySet();
for (Integer key : keySet) {
XSSFRow row = sheet.createRow(rowIndex++);
String line = formattedReport.get(key);
String[] strArr = line.split("##");
int cellCount = 0;
for (String str : strArr) {
XSSFCell cell = row.createCell(cellCount++);
cell.setCellValue(str);
}
}
return workbook;
} catch (Exception e) {
e.printStackTrace();
}
return null; //or return new XSSFWorkbook();
}
这应该按照你想要的方式工作。它使用 Map,因此您必须将其更改为使用 ArrayList,但它的功能应该没有什么不同。
关于 java | Apache POI |如何在不创建行的情况下避免空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39152406/