我想制作一个像这样的Excel工作表:
NAME | ADDRESS | PH
====================
Dad | IND | 123
Mom | IND | 123
Me | IND | 123
Dad
,Mom
和Me
位于列表中。我已经尝试过制作代码,但似乎错了。它不是逐行写入,而是覆盖每个循环中的所有内容。这是代码:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
Row row1 = sheet.createRow((short) 0);
row1.createCell(0).setCellValue("Name");
row1.createCell(1).setCellValue("Address");
row1.createCell(2).setCellValue("Ph");
List<pegawai> list_pegawai = test.list_pegawai();
int a = list_pegawai.size();
for (pegawai p : list_pegawai) {
for (i = 1; i <= a; i++) {
Row row2 = sheet.createRow((short) i);
row2.createCell(0).setCellValue(p.getName());
row2.createCell(1).setCellValue(p.getAddress());
row2.createCell(2).setCellValue(p.getPh());
}
}
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Documents\\workbook.xls");
wb.write(fileOut);
fileOut.close();
JOptionPane.showMessageDialog(null, "SUCCESS");
谢谢你的家伙&#39;回答和帮助:)
答案 0 :(得分:3)
试
int i = 1;
for (pegawai p : list_pegawai) {
Row row2 = sheet.createRow(i++);
row2.createCell(0).setCellValue(p.getName());
row2.createCell(1).setCellValue(p.getAddress());
row2.createCell(2).setCellValue(p.getPh());
}
你已经在列表中进行迭代,不需要做两次。您不希望每次都创建新的row
答案 1 :(得分:1)
尝试使用以下代码行从java创建excel表。在这两者之间,您可以使用任何api从数据库插入数据来进行数据库调用。
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});
Set<String> keyset = data.keySet();
short rownum = 0;
for (String key : keyset) {
HSSFRow row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
HSSFCell 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 {
FileOutputStream out = new FileOutputStream(new File("D:\\new.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}