[英]Exporting data from multiple arrayLists to single excel sheet using java
I have two arraylists each containing certain integer values, my challenge is to print the each arraylist data in each column in the excel sheet using java.我有两个数组列表,每个数组列表都包含某些整数值,我的挑战是使用 java 在 Excel 工作表的每一列中打印每个数组列表数据。 For this I have used apache POI.
为此,我使用了 apache POI。 When I execute the below code only one column is writing and the other column is empty.
当我执行以下代码时,只有一列正在写入,另一列是空的。
package basic;
import java.io.IOException;
import java.util.*;
public class excel {
public static void main(String[] args) throws IOException, InterruptedException {
SimpleExcelWriterExample.createRecord();
List<Integer> values1=Arrays.asList(1,2,3,4,5,6);
List<Integer> values2=Arrays.asList(1,2,3,4,5,6);
SimpleExcelWriterExample.AddRecord(values1,0);
SimpleExcelWriterExample.AddRecord(values2,1);
SimpleExcelWriterExample.Add();
}
}
SimpleExcelWriterExample class is below SimpleExcelWriterExample 类如下
package basic;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.usermodel.*;
class SimpleExcelWriterExample {
public static XSSFWorkbook workbook;
public static XSSFSheet worksheet;
public static FileOutputStream fileOut;
public static XSSFRow row;
public static XSSFCell cell;
public static void createRecord()throws IOException {
fileOut = new FileOutputStream("C:\\Users\\DELL\\workspace\\wipro1\\src\\basic\\New.xlsx");
workbook = new XSSFWorkbook();
worksheet = workbook.createSheet("POI Worksheet");
System.out.println("Sheet creadted successfully");
}
public static void AddRecord(List<Integer> values, int col) throws IOException {
for (int i = 0; i < values.size(); i++) {
row = worksheet.createRow(i);
cell = row.createCell(col);
cell.setCellValue(values.get(i));
//System.out.println(cellAj.getStringCellValue());
}
}
public static void Add() throws IOException {
workbook.write(fileOut);
}
}
-The output I am getting is below enter image description here - 我得到的输出低于在此处输入图像描述
Please help me sort out this problem, Thanks in advance.请帮我解决这个问题,提前致谢。
Sheet.createRow
always creates a new empty row in the sheet. Sheet.createRow
总是在工作表中创建一个新的空行。 So in your AddRecord
method do所以在你的
AddRecord
方法中做
row = worksheet.getRow(i); if (row == null) row = worksheet.createRow(i);
That first tries getting the row and only if the row is not present already, then it creates the row.首先尝试获取该行,并且仅当该行不存在时,它才会创建该行。
So full AddRecord
method could look like:所以完整的
AddRecord
方法可能如下所示:
public static void AddRecord(List<Integer> values, int col) throws IOException {
for (int i = 0; i < values.size(); i++) {
row = worksheet.getRow(i); if (row == null) row = worksheet.createRow(i);
cell = row.createCell(col);
cell.setCellValue(values.get(i));
//System.out.println(cellAj.getStringCellValue());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.