如何使用 Java Apache POI 在 excel 中添加标题列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33735173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add header column in excel using Java Apache POI?
提问by Madhusudan
I am writing a java program in which I have to take data from XML file and put it into excel file. While doing this I have to create row headers and add data accordingly.
我正在编写一个 java 程序,我必须从 XML 文件中获取数据并将其放入 excel 文件中。在执行此操作时,我必须创建行标题并相应地添加数据。
I know how to create column headers. I can do it in following way:
我知道如何创建列标题。我可以通过以下方式做到这一点:
....
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("EDR Raw Data");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Header1");
header.createCell(1).setCellValue("Header2");
header.createCell(2).setCellValue("Header3");
header.createCell(3).setCellValue("Header4");
....
It creates excel file as shown below:
But I want my excel file looks like below:
但我希望我的 excel 文件如下所示:
I am not getting a way to do this. It's not good idea to create required number of rows individually. Is there any way by which we can create a column and add all header in that column?
我没有办法做到这一点。单独创建所需的行数不是一个好主意。有什么方法可以创建一列并在该列中添加所有标题?
The way I tried to do this is:
我尝试这样做的方法是:
....
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("EDR Raw Data");
sheet.createRow(0).createCell(0).setCellValue("header1");
sheet.createRow(1).createCell(0).setCellValue("header2");
sheet.createRow(2).createCell(0).setCellValue("header3");
sheet.createRow(3).createCell(0).setCellValue("header4");
...
But in my case I have to give 100+ row labels. SO this won't be efficient way.
但就我而言,我必须给出 100 多个行标签。所以这不是有效的方式。
采纳答案by Gagravarr
Just create one row for each header, and populate the first cell in each!
只需为每个标题创建一行,并填充每个标题的第一个单元格!
Something like:
就像是:
String[] headers = new String[] { "Header1", "Header2", "Header3" };
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("EDR Raw Data");
for (int rn=0; rn<headers.length; rn++) {
Row r = sheet.createRow(rn);
r.createCell(0).setCellValue(headers[rn]);
}
Then when populating your data, do sheet.getRow(rownumber)
to get the existing row, and populate the remaining cells of interest in it
然后在填充数据时,sheet.getRow(rownumber)
获取现有行,并填充其中感兴趣的剩余单元格