/**
* 写excel文件 * @param response
* @param list <string[]> Excel表格内容
* @param fileName 路径+文件名
* @param titleName 工作表标签
* @param excelDataRow [] 标题
* @throws IOException
* @throws RowsExceededException
* @throws WriteException
*/
public static void writeExcel(HttpServletResponse response, List<Object[]> list,
String fileName, String titleName,String[]excelDataRow) throws IOException, RowsExceededException,
WriteException {
WritableWorkbook book = null;
try {
// File file = new File(fileName);
// book = Workbook.createWorkbook(file);//得到一个可以写的book对象
OutputStream os = response.getOutputStream();
book = Workbook.createWorkbook(os);
response.setContentType("application/x-msdownload;");
// response.setHeader("Content-Disposition",
// "attachment; filename=\"" + java.net.URLEncoder.encode(fileName,
// "UTF-8") + ".xls\"");
response.setHeader("Content-disposition", "attachment; filename="
+ (new String(fileName.getBytes("GBK"), "ISO-8859-1")) + ".xls");
response.setContentType("application/ms-excel;");
System.out.println("响应对象输出流:" + response.getOutputStream());
WritableSheet sheet = book.createSheet(titleName, 0);// 写一个sheet
WritableFont fontHead = new WritableFont(WritableFont.TAHOMA, 15,
WritableFont.BOLD);// 字体
WritableCellFormat formatHead = new WritableCellFormat(fontHead);
formatHead.setAlignment(jxl.format.Alignment.CENTRE);// 标题居中
int colspan = 1;
colspan = excelDataRow.length;// 取出excel的列数以便title跨列
Label labTitle = new Label(0, 0, titleName, formatHead);
sheet.addCell(labTitle);// 写标题
sheet.mergeCells(0, 0, colspan - 1, 0);// 从(0,0)到(colspan-1,0)单元格合并
/**
* 设置单元格每列的大小
* ---begin
*/
sheet.setColumnView(0, 18);
。。。。。。。。
/**
* 设置单元格每列的大小
* ---end
*/
for(int j = 0; j < excelDataRow.length; j++){
Label labValue = new Label(j, 1, excelDataRow[j]);// j:列,第一行,excelDataRow[j]:value
sheet.addCell(labValue);
}
for (int i = 0; i < list.size(); i++) {
Object[] objectArray = list.get(i);
for (int j = 0; j < objectArray.length; j++) {
Label labValue = new Label(j, i + 2, StringUtil.convertToString(objectArray[j]));// j:列,i:行,objectArray[j]:value
sheet.addCell(labValue);
}
}
book.write();
} finally {
book.close();
}
}