您的位置:首页 > 编程语言 > Java开发

Java实现导出Excel文件

2016-05-18 22:47 381 查看
/**

* <p>

* Discription:[导出excel]

* </p>

*

* @param response

* @param list 要导出的数据集合

* @param fileName

* @param sheetName

* @throws Exception

*/

public static void exportXls(HttpServletResponse response, List<String[]> list, String fileName,

String sheetName) throws Exception

{

if (list == null || list.size() == 0)

{

return;

}

// 获取总行数

int rowNum = list.size();

// 获得总列数

int cellNum = list.get(0).length;

// 创建Excel文档

HSSFWorkbook hwb = new HSSFWorkbook();

// sheet对应一个工作页

HSSFSheet sheet = hwb.createSheet(sheetName);

for (int i = 0; i < rowNum; i++)

{

// 创建一行

HSSFRow row = sheet.createRow(i);

// 插入一行数据

for (int j = 0; j < cellNum; j++)

{

HSSFCell cell = row.createCell(j);

cell.setCellValue(list.get(i)[j]);

}

}

// 创建文件输出流,准备输出电子表格

ByteArrayOutputStream os = new ByteArrayOutputStream();

hwb.write(os);

byte[] content = os.toByteArray();

InputStream is = new ByteArrayInputStream(content);

response.reset();

response.setContentType("application/vnd.ms-excel;charset=utf-8");

response.setHeader("Content-Disposition",

"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));

ServletOutputStream out = response.getOutputStream();

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

try

{

bis = new BufferedInputStream(is);

bos = new BufferedOutputStream(out);

byte[] buff = new byte[2048];

int bytesRead;

while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))

{

bos.write(buff, 0, bytesRead);

}

} catch (IOException e)

{

throw e;

} finally

{

if (bis != null)

bis.close();

if (bos != null)

bos.close();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: