ExcelHelp帮助类
public class ExcelHelper {
private static ExcelHelper excelHelper = new ExcelHelper();
public synchronized static ExcelHelper getInstance(){
if (excelHelper == null) {
excelHelper = new ExcelHelper();
}
return excelHelper;
}
public WritableWorkbook createWritableWorkbook(File out,Workbook wb) throws IOException {
WorkbookSettings ws = new WorkbookSettings();
FileUtils.makeDirectory(out);
// ws.setEncoding(ENCODE_WHEN_READING); // 关键代码,解决中文乱码
WritableWorkbook wwb = Workbook.createWorkbook(out, wb, ws);
return wwb;
}
public WritableSheet addCell(WritableSheet sheet,int c, int r, Object cont, CellFormat st) throws Exception{
WritableCell cell = null;
if(null == cont ){
cell = new Blank(c, r, st);
}
else if(cont instanceof Integer ) {
cell = new jxl.write.Number(c, r,(Integer)cont , st);
}
else if (cont instanceof Number )
{
cell = new jxl.write.Number(c, r,((Number)cont).doubleValue(), st);
}
else if (cont instanceof Date )
{
String date = DateUtils.convertDateToString((Date)cont);
cell = new Label(c, r, date,st);
}
else {
cell = new Label(c, r, cont.toString(), st);
}
sheet.addCell(cell);
return sheet;
}
}
action:
public void excel() throws Exception {
QueryFilter queryFilter = QueryFilter.buildFromHttpRequest(Struts2Utils
.getRequest());
List<Information> list = assetsManager.findAsset(queryFilter);
//样板Excel
String examplePath = Struts2Utils.getAppRootPath() + "\\sources\\test.xls";
//当前时间
Long currentDate = System.currentTimeMillis();
ServletOutputStream responOut = Struts2Utils.getResponse().getOutputStream();
WritableWorkbook wwb = assetsManager.excelOut(list,responOut,examplePath);
UploadFile.downloadExcelFile(wwb, Struts2Utils.getResponse(), "test.xls");
}
manager:
public WritableWorkbook excelOut(List<Information> list,
ServletOutputStream responOut, String examplePath) throws Exception {
ExcelHelper helper = ExcelHelper.getInstance();
WritableWorkbook wwb = helper.createWritableWorkbook(responOut,
examplePath);
sheetExcel(helper, wwb, list);
return wwb;
}
public void sheetExcel(ExcelHelper helper, WritableWorkbook wwb,
List<Information> list) throws Exception {
WritableSheet[] sheets = wwb.getSheets();
for (int i = 1; i <= list.size(); i++) {
Information asset = list.get(i - 1);
if(asset.getAsstState() != null && "01".equals(asset.getAsstState())){
WritableSheet sheet1 = sheets[0];
sheet1.insertRow(4+m);
sheet1 = helper.addCell(sheet1, 0, 4 + m, asset.getSindex());
....................