不按模板导出excel并合并单元格

java代码:

/**
     * 下载清单
     * @param response
     * @param purchaseListQueryVo
     * @param request
     */
    @RequestMapping(value = "/downloadList", method = RequestMethod.POST)
    public ResponseEntity<byte[]> downloadList(HttpServletResponse response, PurchaseListQueryVo purchaseListQueryVo, HttpServletRequest request) {
        ResponseEntity<byte[]> responseEntity = null;
        //获取前台额外传递过来的查询条件
        if(log.isDebugEnabled()){
            log.debug("purchaseListQueryVo:{}",purchaseListQueryVo);
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            List<Map<String, Object>> postCheckList= purchaseListService.downloadList(getMap(purchaseListQueryVo));
            String fileName = java.net.URLEncoder.encode("清单导出.xlsx", "UTF-8");

            //生成EXCEL XLSX格式
            this.exportData(postCheckList, byteArrayOutputStream,purchaseListQueryVo);
            //设置响应头让浏览器正确显示下载
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            responseEntity = new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

  

public void exportData(List<Map<String, Object>> postCheckList, OutputStream outputStream,PurchaseListQueryVo purchaseListQueryVo) {

        String orderStartTime = purchaseListQueryVo.getOrderStartTime().replace("-", "/").substring(0,10);
        String orderEndTime = purchaseListQueryVo.getOrderEndTime().replace("-", "/").substring(0,10);
        String header = null;
        if(Lang.isEmpty(purchaseListQueryVo.getOrderStartTime())||Lang.isEmpty(purchaseListQueryVo.getOrderEndTime())){
            header = " 购货清单";
        }else{
            header = orderStartTime + "-"+ orderEndTime + " 购货清单";
        }

        //EXCEL标题2018-04-26
        List<String> titles = Arrays.asList(new String[]{"序号","太平订单号/礼包账单号", "总公司", "采购员/礼包创建员机构", "部门", "采购员/礼包创建员", "采购员/礼包创建员账号","下单时间/账单时间",
                "支付方式","应收凭证号","商品名称","订购数量","单价","商品总价","不含税金额","税额"});
        //EXCEL列
        List<List<Object>> rows = new ArrayList<>();

        //从给定数据获取指定列作为EXCEL列数据
        for (Map<String, Object> map: postCheckList) {
            List<Object> row = new ArrayList<>();

            //序号
            row.add(map.get("ROWNUM"));
            //太平订单号
            row.add(map.get("ORDERNO"));
            //总公司
            row.add(map.get("PARENTCOMPANY"));
            //采购员机构
            row.add(map.get("INVOICENAME"));
            //部门
            row.add(map.get("DEPARTMENT"));
            //采购员
            row.add(map.get("REALNAME"));
            //采购员账号
            row.add(map.get("USERNAME"));
            //下单时间
            row.add(map.get("DATECREATED"));
            //支付方式
            row.add(map.get("PAYNAME"));
            //应收凭证号
            row.add(map.get("VOUCHERNO"));
            //商品名称
            row.add(map.get("PRODUCTNAME"));
            //订购数量
            row.add(map.get("COUNT"));
            //单价
            row.add(new BigDecimal(String.valueOf(map.get("SALEPRICE"))).setScale(2,BigDecimal.ROUND_HALF_UP).toPlainString());
            //商品总价
            row.add(new BigDecimal(String.valueOf(map.get("COMMODITYAMOUNT"))).setScale(2,BigDecimal.ROUND_HALF_UP).toPlainString());
            //不含税金额
            row.add(new BigDecimal(String.valueOf(map.get("NOTAXAMOUNT"))).setScale(2,BigDecimal.ROUND_HALF_UP).toPlainString());
            //税额
            row.add(new BigDecimal(String.valueOf(map.get("TAXAMOUNT"))).setScale(2,BigDecimal.ROUND_HALF_UP).toPlainString());
            rows.add(row);
        }
        XSSFWorkbook xwb = excelService.purchaseListExcelForXLSX(header,titles, rows, "清单");
        try {
            xwb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                xwb.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
/**
	 * 专业公司购货清单生成Excel对象
	 * @param titles 表头
	 * @param rows 数据行
	 * @param sheetName 工作表名
	 * @return
	 */
	public XSSFWorkbook purchaseListExcelForXLSX(String header,List<String> titles, List<List<Object>> rows, String sheetName) {
		XSSFWorkbook xwb = new XSSFWorkbook();
		XSSFSheet sheet = xwb.createSheet(Lang.isEmpty(sheetName) ? "sheet1" : sheetName);

		//创建第一行头部并设置行高及样式
		sheet.addMergedRegion(new CellRangeAddress(0,0,0,titles.size()-1));
		XSSFRow row1 = sheet.createRow(0);
		row1.setHeight((short)600);
		//标题头部样式
		//设置字体
		XSSFFont fontHeader = xwb.createFont();
		fontHeader.setFontName("宋体");
		fontHeader.setFontHeightInPoints((short)16);
		fontHeader.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 字体加粗
		XSSFDataFormat formatHeader = xwb.createDataFormat();
		//设置单元格格式
		XSSFCellStyle styleHeader = xwb.createCellStyle();
		styleHeader.setFont(fontHeader);
		styleHeader.setDataFormat(formatHeader.getFormat("@"));  //设置输入格式为文本格式
		styleHeader.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		styleHeader.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
		styleHeader.setWrapText(true);
		XSSFCell cell1 = row1.createCell(0);
		cell1.setCellStyle(styleHeader);
		cell1.setCellValue(new XSSFRichTextString(header));

		//创建第一行并设置行高
		XSSFRow row = sheet.createRow(1);
		row.setHeight((short)400);
		//标题样式设置
		//设置字体
		XSSFFont fontTitle = xwb.createFont();
		fontTitle.setFontName("宋体");
		fontTitle.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 字体加粗
		fontTitle.setFontHeightInPoints((short)10);
		XSSFDataFormat format = xwb.createDataFormat();
		//设置单元格格式
		XSSFCellStyle styleTitle = xwb.createCellStyle();
		styleTitle.setFont(fontTitle);
		styleTitle.setDataFormat(format.getFormat("@"));  //设置输入格式为文本格式
		styleTitle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		styleTitle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
		styleTitle.setWrapText(true);

		//主体样式设置
		//设置字体
		XSSFFont font = xwb.createFont();
		font.setFontName("宋体");
		font.setFontHeightInPoints((short)10);
		//设置单元格格式
		XSSFCellStyle style = xwb.createCellStyle();
		style.setFont(font);
		style.setDataFormat(format.getFormat("@"));  //设置输入格式为文本格式
		style.setAlignment(XSSFCellStyle.ALIGN_LEFT);
		style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
		style.setWrapText(true);

		//设置单元格内容
		int columnCount = titles.size();
		for(int i = 0; i < columnCount; i++){
			XSSFCell cell = row.createCell(i);
			cell.setCellStyle(styleTitle);
			cell.setCellValue(new XSSFRichTextString(titles.get(i)));
			if(i==0){
				sheet.setColumnWidth(i, 1500);
			}else if(i==10){
				sheet.setColumnWidth(i, 6000);
			}else{
				sheet.setColumnWidth(i, 4000);
			}

			sheet.setDefaultColumnStyle(i, style);
		}

		Integer seqStartRow = null, seqColumn = 0;
		String seqPrevious = null;
		//太平订单号
		Integer orderNoStartrow = null, orderNoColumn = 1;
		String orderNoPrevious = null;
		//总公司
		Integer parentcompanyStartrow = null, parentcompanyColumn = 2;
		String parentcompanyPrevious = null;
		//采购员机构
		Integer invoicenameStartrow = null, invoicenameColumn = 3;
		String invoicenamePrevious = null;
		//部门
		Integer departmentStartrow = null, departmentColumn = 4;
		String departmentPrevious = null;
		//采购员
		Integer realnameStartrow = null, realnameColumn = 5;
		String realnamePrevious = null;
		//采购员账号
		Integer usernameStartrow = null, usernameColumn = 6;
		String usernamePrevious = null;
		//下单时间
		Integer datecreatedStartrow = null, datecreatedColumn = 7;
		String datecreatedPrevious = null;
		//支付方式
		Integer paynameStartrow = null, paynameColumn = 8;
		String paynamePrevious = null;
		//应收凭证号
		Integer vouchernoStartrow = null, vouchernoColumn = 9;
		String vouchernoPrevious = null;

		Map<String, Object> returnMap;
		// 写入数据行
		XSSFCell cell;
		int rowIdx = 2;
		Map<Object, Integer> seqMap = new HashMap<>();
		int seq = 0;
		String lastOrderNo = null;
		try {
			for(List<Object> dr : rows) {
				row = sheet.createRow(rowIdx);
				for(int di=0; di < dr.size(); di++) {
					if(di == 0) {
						if(seqMap.containsKey(dr.get(1))) {
							seq = seqMap.get(dr.get(1));
						} else {
							seq++;
							seqMap.put(dr.get(1), seq);
						}
					}
					cell = row.createCell(di);
					cell.setCellStyle(style);
					String cellValue = "";
					if(Lang.isEmpty(dr.get(di))){
						cellValue = "";
					}else{
						cellValue = dr.get(di)+"";
					}

					if(rowIdx - 2 != rows.size()-1){
						if(di == 0){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,String.valueOf(seq),seqPrevious,seqStartRow,seqColumn, dr.get(1).equals(lastOrderNo));
							seqPrevious = (String) returnMap.get("previousValue");
							seqStartRow = (Integer) returnMap.get("startRow");
						} else if(di == 1){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,orderNoPrevious,orderNoStartrow,orderNoColumn,true);
							orderNoPrevious = (String) returnMap.get("previousValue");
							orderNoStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 2){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,parentcompanyPrevious,parentcompanyStartrow,parentcompanyColumn,dr.get(1).equals(lastOrderNo));
							parentcompanyPrevious = (String) returnMap.get("previousValue");
							parentcompanyStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 3){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,invoicenamePrevious,invoicenameStartrow,invoicenameColumn,dr.get(1).equals(lastOrderNo));
							invoicenamePrevious = (String) returnMap.get("previousValue");
							invoicenameStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 4){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,departmentPrevious,departmentStartrow,departmentColumn,dr.get(1).equals(lastOrderNo));
							departmentPrevious = (String) returnMap.get("previousValue");
							departmentStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 5){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,realnamePrevious,realnameStartrow,realnameColumn,dr.get(1).equals(lastOrderNo));
							realnamePrevious = (String) returnMap.get("previousValue");
							realnameStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 6){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,usernamePrevious,usernameStartrow,usernameColumn,dr.get(1).equals(lastOrderNo));
							usernamePrevious = (String) returnMap.get("previousValue");
							usernameStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 7){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,datecreatedPrevious,datecreatedStartrow,datecreatedColumn,dr.get(1).equals(lastOrderNo));
							datecreatedPrevious = (String) returnMap.get("previousValue");
							datecreatedStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 8){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,paynamePrevious,paynameStartrow,paynameColumn,dr.get(1).equals(lastOrderNo));
							paynamePrevious = (String) returnMap.get("previousValue");
							paynameStartrow = (Integer) returnMap.get("startRow");
						} else if(di == 9){
							returnMap =createOrMargedCell(sheet,row,style,rowIdx,cellValue,vouchernoPrevious,vouchernoStartrow,vouchernoColumn,dr.get(1).equals(lastOrderNo));
							vouchernoPrevious = (String) returnMap.get("previousValue");
							vouchernoStartrow = (Integer) returnMap.get("startRow");
						}else{
							cell.setCellValue(new XSSFRichTextString(cellValue));
						}
					}else{
						cell.setCellValue(new XSSFRichTextString(cellValue));
					}

				}
				lastOrderNo = orderNoPrevious;
				rowIdx ++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xwb;
	}

  

 

原文地址:https://www.cnblogs.com/luoxianwei/p/9335920.html

时间: 2024-10-07 12:35:53

不按模板导出excel并合并单元格的相关文章

WPF 导出Excel(合并单元格)

DataTable 导出Excel(导出想要的列,不想要的去掉) enum Columns{A1=1,B1,B2,B3,B4,B5} MisroSoft.Office.Interop.Excel.Application excelApp=MisroSoft.Office.Interop.Excel.Application excelApp(); Workbook wb=excelApp.Workboype.Missing);//创建工作薄 Worksheet ws=(Worksheet )wb.

转:jxl导出excel(合并单元格)

Demo 代码如下: 1 import java.io.*; 2 import jxl.*; 3 import jxl.format.UnderlineStyle; 4 import jxl.write.*; 5 public class CreateXLS { 6 public static void main(String args[]) { 7 try { 8 //打开文件 9 WritableWorkbook book= Workbook.createWorkbook(new File(

.net读取Excel转datatable、.net读取的Excel存在合并单元格并且转成datatable

项目中经常会遇到Excel导入数据,Excel的模板会可能是存在合并单元格的,模板如下图所示 读取时需要填充合并单元格的值,转成datatable单元格值时,填充合并单元格的值,如下图所示: 合并单元格的值填充,这种格式的datatable使用SqlBulkCopy批量导入更为方便 Excel转datatable方法代码: /// <summary> /// Excel转DataTable /// </summary> /// <param name="filePa

用NPOI创建Excel、合并单元格、设置单元格样式、边框的方法

今天在做项目中,遇到使用代码生成具有一定样式的Excel,找了很多资料,最后终于解决了,Excel中格式的设置,以及单元格的合并等等.下面就介绍下,使用NPOI类库操作Excel的方法. 1.首先我们先在内存中生成一个Excel文件,代码如下:   HSSFWorkbook book = new HSSFWorkbook();        ISheet sheet = book.CreateSheet("Sheet1"); 2.然后在新创建的sheet里面,创建我们的行和列,代码如下

Java poi导入excel(合并单元格的excel)(转)

poi导入excel代码示例 原文地址:https://mbd.baidu.com/newspage/data/landingshare?pageType=1&isBdboxFrom=1&context=%7B%22nid%22%3A%22news_9588929214493290157%22%2C%22sourceFrom%22%3A%22bjh%22%7D 原文地址:https://www.cnblogs.com/zbq6/p/12501683.html

在Asp.Net MVC中使用NPOI插件实现对Excel的操作(导入,导出,合并单元格,设置样式,输入公式)

前言 NPOI 是 POI 项目的.NET版本,它不使用 Office COM 组件,不需要安装 Microsoft Office,目前支持 Office 2003 和 2007 版本. 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 3.POI读取Excel有两种格式一个是HSSF,另一个是XSSF. HSSF和XSSF的区别如下: HSSF

带复杂表头合并单元格的HtmlTable转换成DataTable并导出Excel(转)

步骤: 一.前台JS取HtmlTable数据,根据设定的分隔符把数据拼接起来 <!--导出Excel--> <script type="text/javascript"> //导出Excel function exportExcel() { var data = ""; $("#divRptTable").find("table").find("tr").each(function

【转】C# DataTable 导出 Excel 进阶 多行表头、合并单元格、中文文件名乱码

本文原创地址:http://blog.csdn.net/ranbolwb/article/details/8083983 ,转载请保留本行. 本例子是上一篇 DataTable 导出 Excel 的进阶,除了上一篇提到的处理乱码问题,本例还添加了处理多行表头.合并单元格的功能及处理中文文件名乱码问题,应该可以满足日常开发的需要了. 废话不多说了,直接上代码: [C#] 可以写单独类 1 using System; 2 using System.Collections.Generic; 3 usi

NPOI_winfrom导出Excel表格(合并单元格、规定范围加外边框、存储路径弹框选择)

1.导出 1 private void btn_print_Click(object sender, EventArgs e) 2 { 3 DataTable dtNew = new DataTable(); 4 5 dtNew.Columns.Add(new DataColumn("commodity_name", typeof(object))); 6 dtNew.Columns.Add(new DataColumn("specifications", type