/**
* 将数据写入到excel中
*
* @param os
* 创建Excel的输出流
* @param datalines
* 要插入的数据源
* @param fileName
* excel表名称
*/
public static void exportExcel(HttpServletResponse response,
List<String[]> datalines, String fileName ) {
WritableWorkbook workbook = null;
OutputStream os =null;
try {
os = response.getOutputStream();// 取得输出流
response.setCharacterEncoding('UTF-8');
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(fileName.getBytes("gb2312"), "iso8859-1")+".xls");//fileName为下载时用户看到的文件名利用jxl 将数据从后台导出为excel
response.setHeader("Content-Type", "application/msexcel");
//给单元格设置一个统一的格式
WritableCellFormat wcformat = getExcelCellFormat();
//创建一个excel
workbook = Workbook.createWorkbook(os);
//创建一个sheet
WritableSheet sheet = workbook.createSheet(fileName, 0);
// 写入数据
for (int i = 0; i < datalines.size(); i++) {
String[] lines = datalines.get(i);//一行数据
for (int j = 0; j < lines.length; j++) {//列
sheet.setColumnView(j, 30);// 设置单元格宽度
Label label = new Label(j, i, lines[j], wcformat);
sheet.addCell(label);//填充单元格
}
}
workbook.write();
} catch (RowsExceededException e) {
LogUtil.error(e.getMessage(),e);
} catch (WriteException e) {
LogUtil.error(e.getMessage(),e);
} catch (IOException e) {
LogUtil.error(e.getMessage(),e);
} catch (IllegalArgumentException e) {
LogUtil.error(e.getMessage(),e);
} catch (IllegalAccessException e) {
LogUtil.error(e.getMessage(),e);
} catch (Exception e) {
LogUtil.error(e.getMessage(),e);
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (WriteException e) {
LogUtil.error(e.getMessage(),e);
} catch (IOException e) {
LogUtil.error(e.getMessage(),e);
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
LogUtil.error(e.getMessage(),e);
}
}
}
}
public static WritableCellFormat getExcelCellFormat() throws Exception {
WritableCellFormat wcformat = new WritableCellFormat();
wcformat.setBorder(Border.ALL, BorderLineStyle.THIN);
return wcformat;
}
利用jxl 将数据从后台导出为excel
最新推荐文章于 2024-07-31 07:00:00 发布