c#导出EXCEL合并单元格代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#导出EXCEL合并单元格代码相关的知识,希望对你有一定的参考价值。

c#导出EXCEL合并单元格,使用字符串编写一个动态table,然后放进label中显示,这步已经实现了。现在需要把表格导出到本地,而且有些单元格是合并的,希望能按照在网页上显示的格式原原本本的导出到excel

Excel._Application exc=new Excel.ApplicationClass();
exc.Application.Workbooks.Add(true);
Excel._Worksheet ws=new Excel.WorksheetClass();
ws=(Excel._Worksheet)exc.ActiveSheet; //取得当前worksheet

Excel.Range r;
r=ws.get_Range(ws.Cells[1,1],ws.Cells[1,6]); //取得合并的区域
r.MergeCells=true;
参考技术A 这种合并通常有空格的,既使没空格也有规律的,你拉出数据就可以做了具体你可以用数据下分列,和MID等来实现,要看你是什么样的数据 参考技术B c#导出EXCEL合并单元格,使用字符串编写一个动态table,然后放进label中显示,这步已经实现了。现在需要把表格导出到本地,而且有些单元格是合并的,希望能按照在网页上显示的格式原原本本的导出到excel

不按模板导出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;
	}

  

 

 

以上是关于c#导出EXCEL合并单元格代码的主要内容,如果未能解决你的问题,请参考以下文章

java poi 导出 excel时 ,合并单元格的问题

nodejs+ejsexcel做excel复杂导出,合并单元格

easyexcel合并单元格导出内存溢出

C# 获取Excel中的合并单元格

记录解析具有合并单元格的Excel

poi 导出excel 怎么设置合并的单元格自动换行