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

  直接上代码吧

/**
 * 
 */
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);
	}

}

  

转载于:https://www.cnblogs.com/interesting-whh/p/11096930.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Java中,要导出带有合并单元Excel文件,可以使用Apache POI库。Apache POI是一个用于操作各种Microsoft Office式文件的Java库。以下是一个简单的示例代码来导出带有合并单元Excel文件: ``` import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; public class ExcelExportExample { public static void main(String[] args) { String[] headers = {"姓名", "学科", "分数"}; String[][] data = {{"小明", "数学", "90"}, {"小明", "英语", "80"}, {"小明", "语文", "95"}}; try (Workbook workbook = new XSSFWorkbook()) { Sheet sheet = workbook.createSheet("成绩表"); Row headerRow = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(headers[i]); } for (int i = 0; i < data.length; i++) { Row dataRow = sheet.createRow(i + 1); for (int j = 0; j < data[i].length; j++) { Cell cell = dataRow.createCell(j); cell.setCellValue(data[i][j]); } } // 合并单元 CellRangeAddress region = new CellRangeAddress(1, 1, 0, 2); sheet.addMergedRegion(region); try (FileOutputStream outputStream = new FileOutputStream("成绩表.xlsx")) { workbook.write(outputStream); } System.out.println("Excel文件导出成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码创建了一个包含姓名、学科和分数的表头和对应的数据行的Excel。然后使用`CellRangeAddress`类来指定需要合并单元,这里示例代码将第一行的第一列到第三列进行合并。最后将Workbook写入到文件输出流中,即可将带有合并单元Excel文件导出成功。 ### 回答2: 在Java导出带有合并单元Excel文件可以通过使用Apache POI库来实现。Apache POI是一个开源的Java库,用于处理Microsoft Office式文件,包括Excel。 首先,确保已经在Java项目中引入了Apache POI库的相关依赖。 接下来,我们需要创建一个Workbook对象(代表一个Excel文件),并设置合并单元样式。可以使用CellStyle对象来定义合并单元样式,例如设置背景颜色、边框等。 然后,创建一个Sheet对象(代表一个Excel工作表),并在其中设置合并单元的区域。可以使用Sheet对象的addMergedRegion方法来实现,指定需要合并单元区域的起始行、起始列、结束行、结束列。 最后,通过创建Row和Cell对象,并设置其值,将数据写入合并单元的位置。 下面是一个简单的示例代码: ```java import org.apache.poi.ss.usermodel.*; public class ExcelExporter { public static void main(String[] args) { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setBorderBottom(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); // 合并第一行的前三列 Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("合并单元"); cell.setCellStyle(style); // 写入文件或进行其他操作 } } ``` 以上代码创建了一个包含合并单元Excel文件,合并了第一行的前三列,并将"合并单元"写入合并单元的位置。可以根据实际需求进行修改和扩展。 希望对你有所帮助! ### 回答3: 在Java导出带有合并单元Excel可以使用Apache POI库来实现。下面是一个简单的示例代码: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; public class ExcelExportDemo { public static void main(String[] args) { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 创建合并单元区域 CellRangeAddress mergeRegion = new CellRangeAddress(0, 0, 0, 3); // 合并单元 sheet.addMergedRegion(mergeRegion); // 创建行 Row row = sheet.createRow(0); // 创建单元 Cell cell = row.createCell(0); // 设置单元内容 cell.setCellValue("合并单元示例"); // 导出Excel文件 try { FileOutputStream outputStream = new FileOutputStream("output.xlsx"); workbook.write(outputStream); outputStream.flush(); outputStream.close(); System.out.println("Excel文件导出成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码创建了一个工作簿和工作表,然后设置合并单元的区域,创建行和单元,并设置单元的值为"合并单元示例"。最后将工作簿导出Excel文件。在Excel中打开导出的文件,可以看到第一行的前四列单元合并为一个单元,并且单元的内容为"合并单元示例"。 注意:在运行代码之前,确保已经导入了Apache POI库的相关依赖。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值