本文实例为大家分享了java使用poi导出Excel的具体代码,供大家参考,具体内容如下
package hyss.util.common; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.util.CellRangeAddress; /** * Excel导出工具类 * @author ts */ public class ExportExcelUtil { //显示的导出表的标题 private String title; //导出表的列名 private String[] rowName ; private List dataList = new ArrayList(); // HttpServletResponse response; //构造方法,传入要导出的数据 public ExportExcelUtil(String title,String[] rowName,List dataList){ this.dataList = dataList; this.rowName = rowName; this.title = title; } /* * 导出数据 * */ public void export() throws Exception{ try{ HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象 HSSFSheet sheet = workbook.createSheet(title); // 创建工作表 // 产生表格标题行 HSSFRow rowm = sheet.createRow(0); HSSFCell cellTiltle = rowm.createCell(0); rowm.setHeightInPoints(25); //设置标题行默认行高 //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】 HSSFCellStyle columnTitleStyle = this.getTitleTopStyle(workbook);//获取标题行样式 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook); //获取列头样式对象 HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1))); cellTiltle.setCellStyle(columnTitleStyle); cellTiltle.setCellValue(title); // 定义所需列数 int columnNum = rowName.length; HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行) rowRowName.setHeightInPoints(25); //将列头设置默认行高 // 将列头设置到sheet的单元格中 for(int n=0;n
实现方法
/* * 实现方法 */ public void exportExcel() throws Exception{ String title = "测试"; String[] rowsName = new String[]{"序号","列头1","列头2","列头3","列头4","列头5"}; List dataList = new ArrayList(); Object[] objs = null; for (int i = 0; i <10; i++) { objs = new Object[rowsName.length]; objs[0] = i; objs[1] = "测试1"; objs[2] = "测试2"; objs[3] = "测试3"; objs[4] = "测试4"; objs[5] = "测试5"; dataList.add(objs); } ExportExcelUtil ex = new ExportExcelUtil(title, rowsName, dataList); ex.export(); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。