我正在努力从数据库中获取数据并在excel上显示。我正在使用Apache poi库来生成excel。
这是生成excel的片段。
public class GenerateReport {
public void showReport() {
List<T> t = sampleDao.getAllData();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = null;
HSSFCell column = null;
HSSFRow row1 = sheet.createRow(1);
HSSFCell c11 = row1.createCell(1);
HSSFCell c12 = row1.createCell(2);
HSSFCell c13 = row1.createCell(3);
HSSFCell c14 = row1.createCell(4);
HSSFCell c15 = row1.createCell(5);
c11.setCellValue("ID");
c12.setCellValue("Date");
c13.setCellValue("Time");
c14.setCellValue("YES/NO");
c15.setCellValue("Action");
for (final T sampleT: t) {
....algo and what should be written
}
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseContentType("application/vnd.ms-excel");
externalContext.setResponseHeader("Content-Disposition",
"attachment; filename=\"Sample Report");
workbook.write(externalContext.getResponseOutputStream());
facesContext.responseComplete();
}
}
// DAO的getter setter
public void setSampleDao(
SampleDao sampleDao) {
this.sampleDao = sampleDao;
}
public SampleDao getSampleDao() {
return sampleDao;
}
}
sampleDao.getAllData();
getAllData()方法返回需要通过查询显示的数据。
我需要帮助如何获取数据以及应该在此for循环中编写的内容
for (final T sampleT: t) {
....algo and what should be written
}
有一个条件,如果c14.setCellValue(“是/否”);是,然后在此单元格c15.setCellValue(“Action”)下,将写入特定操作。
ID日期时间是/否操作
是/没有来自数据库的数据(sampleDao.getAllData();),如果存在,则我将在Action Column中写入特定操作,在获取第二个数据后,它将检查先前的是/否,如果两者相同/或更改,我需要根据它编写Action。
有人可以帮助我
答案 0 :(得分:2)
当你写了这么多时,我不明白为什么它很难填满循环。
这是算法/伪代码......
String previousYesNo=null":
int rowcounter=2;
for (final T sampleT: t) {
create hssf row with rowcounter
create hssf cell for the 5 columns
set data to all the columns from the sampleT object
String yesNo=sampleT.getYesNO();
if(previousYesNo!=null && prviousYesNo.equals(yesNo)){
set action cell value to something
}else{
set action cell value to something else
}
previousYesNo=yesNo;
rowCounter++;
}
在单元格中设置数据:
HSSFRow row = sheet.getRow(rowIdx);
HSSFCell cell = row.getCell(colIdx);
//if its a string.. otherwise choose the correct cell type
cell.setCellType(HSSFCell..CELL_TYPE_STRING);
cell.setCellValue(new HSSFRichTextString(data));
答案 1 :(得分:0)
您可以像这样设置单元格中的数据
`
Cell cell = row.getCell(excelColNum);
if (cell == null) {
cell = row.createCell(excelColNum);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue( cellValue);
`