如何按顺序将数据写入Excel文件 [英] How to write data into Excel file in order
本文介绍了如何按顺序将数据写入Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要按顺序将数据写入Excel文件.
I need to write data into an Excel file in order.
我已经写了这个函数:
private void writeXlFile()
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, List<String>> empData = new HashMap<String, List<String>>();
List<String> name = new ArrayList<String>();
name.add("Employee ID");
name.add("Employee Name");
name.add("Salary");
empData.put("1", name);
name = new ArrayList<String>();
name.add("01");
name.add("bala");
name.add("100000");
empData.put("2", name);
name = new ArrayList<String>();
name.add("02");
name.add("Ganesh");
name.add("100000");
empData.put("3", name);
name = new ArrayList<String>();
name.add("03");
name.add("Krish");
name.add("100000");
empData.put("4", name);
Set<String> keyset = empData.keySet();
int rownum = 0;
for (String key : keyset)
{
Row row = sheet.createRow(rownum++);
List<String> nameList = empData.get(key);
int cellnum = 0;
for (Object obj : nameList)
{
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
{
cell.setCellValue((Date) obj);
}
else if (obj instanceof Boolean)
{
cell.setCellValue((Boolean) obj);
}
else if (obj instanceof String)
{
cell.setCellValue((String) obj);
}
else if (obj instanceof Double)
{
cell.setCellValue((Double) obj);
}
}
}
try
{
String path = separator + "home" + separator + "santhanam" + separator
+ "Desktop" + separator + "write.xls";
FileOutputStream out =
new FileOutputStream(new File(path));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
}
catch (FileNotFoundException e)
{
System.out.println("FileNotFoundException :" + e);
}
catch (IOException e)
{
System.out.println("IOException :" + e);
}
}
它正在工作,但是结果看起来像这样:
It's working, but the result is appearing like this:
02 Ganesh 100000
01 bala 100000
Employee ID Employee Name Salary
03 Kumar 100000
我想在表格的第一行写上员工ID和姓名.
I want to write employee id and name as first row in the sheet.
我该怎么办?
推荐答案
请使用Integer而不是String.
Please use Integer instead of String.
Map<Integer, List<String>> empData = new HashMap<Integer , List<String>>();
,依此类推.它将解决您的问题.
and so on. It will fix your problem.
谢谢Bipin
这篇关于如何按顺序将数据写入Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文