Java使用POI导出Excel

来源:互联网 发布:微商加人软件 编辑:程序博客网 时间:2024/05/16 13:46
package com.cjj.demo;import java.io.IOException;import java.io.OutputStream;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;/** * @author cjj * @date 2017年5月23日 上午10:34:46 */public class Test{public void writeExcel(HttpServletResponse response) throws IOException{//创建excel工作簿Workbook wb = new HSSFWorkbook();//创建第一个sheet(页),命名为 new sheetSheet sheet1 = wb.createSheet("第一个sheet1");//设置列的宽度,setColumnWidth(索引,字符数 * 256(Width的单位是1/256个字符宽度))sheet1.setColumnWidth(0, 30 * 256);sheet1.setColumnWidth(1, 30 * 256);sheet1.setColumnWidth(2, 30 * 256);sheet1.setColumnWidth(3, 20 * 256);//Row 行//Cell 方格// Row 和 Cell 都是从0开始计数的// 创建一行,在页sheet上Row row = sheet1.createRow((short) 0);//设置行的宽度,createRow(索引),setHeight(像素 * 20(Height的单位是1/20个像素点))//row.setHeight((short)(20 * 20));// 设置表头样式HSSFCellStyle headerStyle = (HSSFCellStyle) wb.createCellStyle();//创建样式//headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置居中//headerStyle.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//填充背景色//headerStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);//填充背景色//headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);//选择用户定义的填充模式HSSFFont headerFont = (HSSFFont) wb.createFont();//创建字体headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 字体加粗//headerFont.setColor(HSSFColor.WHITE.index);//字体颜色headerStyle.setFont(headerFont);//将字体应用到当前的样式// 在row行上创建列Cell cell0 = row.createCell(0);Cell cell1 = row.createCell(1);Cell cell2 = row.createCell(2);Cell cell3 = row.createCell(3);//设置列的值cell0.setCellValue("单元格1");cell1.setCellValue("单元格2");cell2.setCellValue("单元格3");cell3.setCellValue("单元格4");//设置列的样式cell0.setCellStyle(headerStyle);cell1.setCellStyle(headerStyle);cell2.setCellStyle(headerStyle);cell3.setCellStyle(headerStyle);//这里list为查询出的数据集合,从第二行开始循环赋值for (int i = 0; i < list.size(); i++) {row = sheet1.createRow((short) (i+1));row.createCell(0).setCellValue(list.get(i).get...());//单元格1row.createCell(1).setCellValue(list.get(i).get...());//单元格2row.createCell(2).setCellValue(list.get(i).get...());row.createCell(3).setCellValue(list.get(i).get...());}//文件名String filename =123.xls;//输出excel文件response.reset();OutputStream os = response.getOutputStream();//创建输出流//下载中文名乱码解决办法response.setHeader("Content-Disposition", "attachment;fileName="+ new String(filename.getBytes("gbk"),"iso-8859-1"));response.setContentType("application/msexcel");wb.write(os);// 把上面创建的工作簿写入到输出流中os.close();//关闭流}}

原创粉丝点击