我有一个项目有一个模型类,Person有三个列:id,name和country,它们正确地持久化到PostgreSQL。结果在List
个对象中正确找到。但我想将List
数据(显示在页面上)导出到Excel。
我创建了一个名为PersonExcelView
的类:
public class PersonExcelView extends AbstractExcelView {
private PersonService personService;
@Override
protected void buildExcelDocument(Map<String, Object> arg0, HSSFWorkbook arg1, HttpServletRequest arg2,
HttpServletResponse arg3) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet excelSheet = workbook.createSheet("PersonList");
setExcelHeader(excelSheet);
List personList = (List) personService.getPersonList();
setExcelRows(excelSheet,personList);
}
public void setExcelHeader(HSSFSheet excelSheet) {
HSSFRow excelHeader = excelSheet.createRow(0);
excelHeader.createCell(0).setCellValue("Id");
excelHeader.createCell(1).setCellValue("Name");
excelHeader.createCell(2).setCellValue("Country");
}
public void setExcelRows(HSSFSheet excelSheet, List personList){
int record = 1;
for (Person person : personService.listPersons()) {
HSSFRow excelRow = excelSheet.createRow(record++);
excelRow.createCell(0).setCellValue(person.getId());
excelRow.createCell(1).setCellValue(person.getName());
excelRow.createCell(2).setCellValue(person.getCountry());
}
}}
这是我的PersonServiceImpl
课程:
@Service
public class PersonServiceImpl implements PersonService {
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
@Override
@Transactional
public void addPerson(Person p) {
this.personDAO.addPerson(p);
}
@Override
@Transactional
public void updatePerson(Person p) {
this.personDAO.updatePerson(p);
}
@Override
@Transactional
public List<Person> listPersons() {
return this.personDAO.listPersons();
}
@Override
@Transactional
public Person getPersonById(int id) {
return this.personDAO.getPersonById(id);
}
@Override
@Transactional
public void removePerson(int id) {
this.personDAO.removePerson(id);
}
@Override
public List<Person> getPersonList() {
// TODO Auto-generated method stub
return listPersons();
}
}
这是我的控制器代码:
@RequestMapping(value = "/export", method = RequestMethod.POST)
public ModelAndView getExcel() {
List personList = (List) personService.getPersonList();
return new ModelAndView("PersonExcelView", "personList", personList);
}
这是JSP:
<a href="SpringMVCHibernate/export">Export</a></h3>
单击导出时,它不会将数据导出到Excel中。错误在哪里?
答案 0 :(得分:0)
使用以下代码将数据导出到Excel工作表,并根据您的代码要求进行更改。
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("PersonList");
XSSFRow row;
for (Object obj : objectArr)// for (Person person : personService.listPersons())
{
Cell cell = row.createCell(cellid++);
cell.setCellValue((String)obj);
}
for(int columnIndex = 0; columnIndex < 24; columnIndex++) {
spreadsheet.autoSizeColumn(columnIndex);
}
if(List.size()!=0)
{
FileOutputStream out;
out = new FileOutputStream(new File(file_path));
workbook.write(out);
out.close();
}