java实现数据的Excel导出(合并单元格、样式等)

摘要:
直接转到代码/***/packagezhongdian.whh。普通阶层;importjava.io。IOException;importjava.io。不支持编码异常;导入java.util。阵列列表;导入java.util。列表导入javax.servlet.http.HttpServletR

  直接上代码吧

/**
 * 
 */
package zhongdian.whh.commonclass;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

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.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.hssf.util.Region;

/**数据导出Excel
 * 2018/9/10
 * @author
 *
 */
public class DataToExcel {
	
	private DataToExcel(){}
	
	/**
	 * 导出Excel
	 * @param response 你懂的
	 * @param excelFile Excel文件
	 * @param fileName 导出的文件名
	 */
	public static void export(HttpServletResponse response , HSSFWorkbook excelFile , String fileName) {
        //写入excel表
		response.reset();
        response.setContentType( "application/octet-stream;charset=GBK" );
        response.setCharacterEncoding("GBK");
        response.setHeader( "Content-Disposition", "attachment;filename=" + processExcelFilename(fileName) + ".xls" );
		try {
			excelFile.write(response.getOutputStream( ));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 导出Excel
	 * @param response 你懂的
	 * @param fileName 导出的文件名
	 * @param columnWidth 列宽
	 * @param rowName 表头
	 * @param dataList 数据以List<List<String>>组织
	 */
	public static void export(HttpServletResponse response , String fileName , int columnWidth , 
			String sheetName , String[] rowName, List<List<String>> dataList){
		HSSFWorkbook excelFile = null;
		try {
			excelFile = toExcel(excelFile, sheetName, columnWidth, rowName, dataList);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		export(response, excelFile, fileName);
	}
	

	/**
	 * 堆叠转换成Excel文件
	 * @param excelFile 堆叠Excel文件,传null则新建
	 * @param table Table
	 * @param sheetName SheetName
	 * @param columnWidth 列宽
	 * @return 堆叠后的Excel文件
	 * @throws IOException
	 */
	public static HSSFWorkbook toExcel(HSSFWorkbook excelFile, String sheetName , int columnWidth
			, String[] rowName, List<List<String>> dataList) throws IOException{
		// 声明一个工作薄
		if (excelFile == null){
			excelFile = new HSSFWorkbook();
		}
        // 生成标题样式
        @SuppressWarnings("unused")
		HSSFCellStyle titleStyle = getTitleStyle( excelFile );
        // 生成标题行样式
        @SuppressWarnings("unused")
        HSSFCellStyle titleRowStyle = getRowTitleStyle( excelFile );
        // 生成数据样式
        HSSFCellStyle cellRowStyle = getCellStyle( excelFile );
        //高亮格式
        HSSFCellStyle styleLight = styleLight(excelFile);
        
        int sheetNum = (int)dataList.size()/60000;
        if(dataList.size()%60000!=0){
        	sheetNum++;
        }
        /**合并单元格的例子
        //表头样式设置
        HSSFRow row0 = sheet.createRow(0);
        createMyCells(0,19,row0,titleRowStyle);
        sheet.addMergedRegion(getMyRegion(0, 2, 0, 0));
        addMyTitle(row0, 0, "跟进人名称");
        sheet.addMergedRegion(getMyRegion(0, 2, 1, 1));
        addMyTitle(row0, 1, "名义欠款金额合计");
        sheet.addMergedRegion(getMyRegion(0, 0, 2, 7));
        addMyTitle(row0, 2, "超期欠款");
        sheet.addMergedRegion(getMyRegion(0, 0, 8, 13));
        addMyTitle(row0, 8, "超期合同数量");
        sheet.addMergedRegion(getMyRegion(0, 0, 14, 18));
        addMyTitle(row0, 14, "超期欠款合同数量");
        
        HSSFRow row1 = sheet.createRow(1);
        createMyCells(0,19,row1,titleRowStyle);
        sheet.addMergedRegion(getMyRegion(1, 2, 2, 2));
        addMyTitle(row1, 2, "超期欠款金额合计");
        sheet.addMergedRegion(getMyRegion(1, 1, 3, 7));
        addMyTitle(row1, 3, "超期时间/月");
        sheet.addMergedRegion(getMyRegion(1, 2, 8, 8));
        addMyTitle(row1, 8, "超期合同数量合计");
        sheet.addMergedRegion(getMyRegion(1, 1, 9, 13));
        addMyTitle(row1, 9, "超期时间/月");
        sheet.addMergedRegion(getMyRegion(1, 2, 14, 14));
        addMyTitle(row1, 14, "1万以下");
        sheet.addMergedRegion(getMyRegion(1, 2, 15, 15));
        addMyTitle(row1, 15, "1万至5万");
        sheet.addMergedRegion(getMyRegion(1, 2, 16, 16));
        addMyTitle(row1, 16, "5万至10万");
        sheet.addMergedRegion(getMyRegion(1, 2, 17, 17));
        addMyTitle(row1, 17, "10万至30万");
        sheet.addMergedRegion(getMyRegion(1, 2, 18, 18));
        addMyTitle(row1, 18, "30万以上");
        */
        for(int k = 0; k < sheetNum; k++){
        	//创建一个sheet
	    	HSSFSheet sheet = excelFile.createSheet();
	    	excelFile.setSheetName(excelFile.getNumberOfSheets() - 1, sheetName+k+"",(short)1); 
	        sheet.setDefaultColumnWidth((short) (columnWidth));
			//Build Excel
	        if(rowName!=null && rowName.length>0) {
	        	//设置表头
		        int columnNum = rowName.length;
		        HSSFRow rowRowName = sheet.createRow(0);                // 在索引0的位置创建行
		        
		        // 将列头设置到sheet的单元格中
		        for(int n=0;n<columnNum;n++){
		            HSSFCell  cellRowName = rowRowName.createCell((short)n);//创建列头对应个数的单元格
		            
		            cellRowName.setEncoding( HSSFCell.ENCODING_UTF_16 );
		            cellRowName.setCellType( HSSFCell.CELL_TYPE_STRING );
		            cellRowName.setCellValue(rowName[n]);//设置列头单元格的值
		            cellRowName.setCellStyle(titleRowStyle);
		        }
	        }
		        
	        int rowIndex = 1;
	        for(int index = k * 60000; index < dataList.size(); index++){
	        	
	        	List<String> dl = dataList.get(index);
	        	HSSFRow row = sheet.createRow(rowIndex);
	        	HSSFCellStyle cellstyle = cellRowStyle;
	        	if(rowIndex%2==1){
	        		cellstyle = styleLight;
	        	}
	        	for(int i = 0; i < dl.size(); i++) {
	        		addCell_whh(row, cellstyle,  dl.get(i), i);
	        	}
	        	rowIndex++;
	        }
        }
		return excelFile;
	}
	
	private static Region getMyRegion(int rf,int rt,int cf,int ct){
		Region region = new Region(); 
        region.setRowFrom(rf);
        region.setRowTo(rt);
        region.setColumnFrom((short) cf);
        region.setColumnTo((short) ct);
        return region;
	}
	private static void createMyCells(int from,int to,HSSFRow rowRowName, HSSFCellStyle titleRowStyle){
		for(int i = from; i < to; i++){
			HSSFCell  cellRowName = rowRowName.createCell((short)i);
			cellRowName.setEncoding( HSSFCell.ENCODING_UTF_16 );
	        cellRowName.setCellType( HSSFCell.CELL_TYPE_STRING );
	        cellRowName.setCellStyle(titleRowStyle);
		}
	}
	
	public static void addCell_whh(HSSFRow row, HSSFCellStyle cellstyle,  String text, int n){
		HSSFCell cell = row.createCell((short)n);
		cell.setCellStyle(cellstyle);
		cell.setEncoding( HSSFCell.ENCODING_UTF_16 );
	    cell.setCellType( HSSFCell.CELL_TYPE_STRING );
        cell.setCellValue(text);
	}
	
	/**
	 * 生成标题样式
	 * @param workbook
	 * @return
	 */
	public static HSSFCellStyle getTitleStyle(HSSFWorkbook workbook){
		HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
		style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		
		style.setBottomBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setRightBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setLeftBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setTopBorderColor(HSSFColor.GREY_50_PERCENT.index);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        
        return style;
	}
	
	/**
	 * 生成行标题样式
	 * @param workbook
	 * @return
	 */
	public static HSSFCellStyle getRowTitleStyle(HSSFWorkbook workbook){
		HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
		style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		
		style.setBottomBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setRightBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setLeftBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setTopBorderColor(HSSFColor.GREY_50_PERCENT.index);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
//        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 10);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        
        return style;
	}
	
	/**
	 * 生成数据样式
	 * @param workbook
	 * @return
	 */
	public static HSSFCellStyle getCellStyle(HSSFWorkbook workbook){
		HSSFCellStyle style = workbook.createCellStyle();
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
		style.setBottomBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setRightBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setLeftBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setTopBorderColor(HSSFColor.GREY_50_PERCENT.index);
        // 生成另一个字体
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        
        return style;
	}
	
	/**
	 * 高亮格式
	 * @param workbook
	 * @return
	 */
	public static HSSFCellStyle styleLight(HSSFWorkbook workbook){
		HSSFCellStyle style = workbook.createCellStyle();
		style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
		//HSSFColor.SKY_BLUE;
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
		style.setBottomBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setRightBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setLeftBorderColor(HSSFColor.GREY_50_PERCENT.index);
		style.setTopBorderColor(HSSFColor.GREY_50_PERCENT.index);
        // 生成另一个字体
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        
        return style;
	}
	
	/**
	 * 预处理导出文件名
	 * @param str
	 * @return
	 */
	public static String processExcelFilename(String str){
		try {
			return java.net.URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "No Name";
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		List<List<String>> dataList = new ArrayList<List<String>>();
		System.out.println((int)100/6000);
	}

}

  

免责声明:文章转载自《java实现数据的Excel导出(合并单元格、样式等)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Linux 的字符串截取很有用。有八种方法。小白也能看懂的mySQL进阶【单表查询】下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

centos LNMP第一部分环境搭建 LAMP LNMP安装先后顺序 php安装 安装nginx 编写nginx启动脚本 懒汉模式 mv /usr/php/{p.conf.default,p.conf} php运行方式SAPI介绍 第二十三节课

centos  LNMP第一部分环境搭建 LAMP安装先后顺序  LNMP安装先后顺序 php安装 安装nginx  编写nginx启动脚本   懒汉模式  mv   /usr/local/php/{p.conf.default,p.conf}  php运行方式SAPI介绍  第二十三节课 推荐搜狐下载地址:http://mirrors.sohu.com/...

zookeeper-分布式协调工具(一),java操作zookeeper

什么是zookeeper 1.Zookeeper是一个分布式开源框架,提供了协调分布式应用的基本服务,它向外部应用暴露一组通用服务——分布式同步、命名服务、集群维护等,简化分布式应用协调及其管理的难度,提供高性能的分布式服务。ZooKeeper本身可以以单机模式安装运行,不过它的长处在于通过分布式ZooKeeper集群,基于一定的策略来保证ZooKeepe...

Apache Commons 工具类介绍及简单使用

转自:http://www.cnblogs.com/younggun/p/3247261.html Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。下面是我这几年做开发过程中自己用过的工具类做简单介绍。 组件 功能介绍 BeanUtils 提供了对于JavaBean进行各种操作,克隆对象,属性等等....

禅道从windows迁移到linux

一、禅道数据库备份 1.1、在Windows下安装的禅道备份数据库 很多人觉得无从下手,甚至数据库账号密码都不知道怎么办,我的是在windows server 2008上安装的禅道,在安装目录下比如我的是C:UsersAdministratorDownloadsxamppzentaoconfigmy.php下有mysql的信息,端口账号密码是不是一下子就有...

mybatis支持jdk8等localdate类型

大家知道,在实体Entity里面,可以使用java.sql.Date、java.sql.Timestamp、java.util.Date来映射到数据库的date、timestamp、datetime等字段 但是,java.sql.Date、java.sql.Timestamp、java.util.Date这些类都不好用,很多方法都过时了。 Java8里面新...

PHP 配置文件中open_basedir选项作用

如下是php.ini中的原文说明以及默认配置: ; open_basedir, if set, limits all file operations to the defined directory ; and below. This directive makes most sense if used in a per-directory or ; pe...