报表poi

记录poi操作

1、Excel表导入

 

  • 创建输入流
  • 创建Workbook对象 wb
  • 判断Wordbook类型
  • 得到工作簿sheet
  • 得到Excel的行和列,循环录入

    以下附部分代码

/**
	 * 导入期初数据
	 * 
	 * @throws IOException
	 */
	public ObjectResponse exportData(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response)
			throws IOException
	{
		// 总行数
		int totalRows = 0;
		// 总条数
		int totalCells = 0;
		User currentUser = getUser();
		ObjectResponse res = isNullUser(currentUser);
		if (res.getCode() == 0)
		{
			return res;
		}
		// 初始化输入流
		InputStream is = null;
		try
		{
			boolean isExcel2003 = true;
			if (isExcel2007(file.getOriginalFilename()))
			{
				isExcel2003 = false;
			}
			// 根据新建的文件实例化输入流
			is = file.getInputStream();
			// 根据excel里面的内容读取客户信息
			/** 根据版本选择创建Workbook的方式 */
			Workbook wb = null;
			// 当excel是2003时
			if (isExcel2003)
			{
				wb = new HSSFWorkbook(is);
			} else
			{// 当excel是2007时
				wb = new XSSFWorkbook(is);
			}
			// 得到第一个shell
			Sheet sheet = wb.getSheetAt(0);
			// 得到Excel的行数
			totalRows = sheet.getPhysicalNumberOfRows();
			// 得到Excel的列数(前提是有行数)
			if (totalRows >= 1 && sheet.getRow(0) != null)
			{
				totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
			}
			Beginning beginning;
			// 循环Excel行数,从第二行开始。标题不入库
						for (int r = 1; r < totalRows; r++)
						{
							Row row = sheet.getRow(r);
							if (row == null)
								continue;
							beginning = new Beginning();
							// 循环Excel的列
							for (int c = 0; c < totalCells; c++)
							{
								Cell cell = row.getCell(c);
								if (null != cell)
								{
									if (c == 0)
									{
										BdmCustomer selectByCustomerName = bdmCustomerService.selectByCustomerName(cell.getStringCellValue());
										if (null == selectByCustomerName)
										{
											res.setMessage("错误");
											res.setCode(0);
											return res;
										}
										beginning.setCompId(selectByCustomerName.getId());
									} else if (c == 1)
									{
										BdmCustomer selectByCustomerName = bdmCustomerService.selectByCustomerName(cell.getStringCellValue());
										if (null == selectByCustomerName)
										{
											res.setMessage("错误");
											res.setCode(0);
											return res;
										}
										beginning.setCustomer_id(selectByCustomerName.getId());
									}
									else if (c == 2)
									{
										beginning.setFlag_exchange((int) cell.getNumericCellValue()); //关系标识
									} else if (c == 3)
									{
										beginning.setBeginningBalance(new BigDecimal(cell.getNumericCellValue()));
									} else if (c == 4)
									{
										beginning.setBeginningDate(cell.getDateCellValue());
									} else if (c == 5)
									{
										beginning.setRemark(cell.getStringCellValue());// 备注
									}
								}
							}
							needService.insertBeginning(beginning);
						}
						res.setMessage("导入成功");
						res.setCode(1);
						is.close();
					} catch (Exception e)
					{
						res.setMessage("系统错误");
						res.setCode(0);
						e.printStackTrace();
					} finally
					{
						if (is != null)
						{
							is.close();
						}
					}
					return res;
				}


	// @描述:是否是2007的excel,返回true是2007
	private boolean isExcel2007(String filePath)
	{
		return filePath.matches("^.+\\.(?i)(xlsx)$");
	}

 

 

 

2、导出Excel

 

  • 创建Excel文档对象    Workbook wb
  • 创建sheet表单对象    Sheet sheet
  • 创建行、列对象        Row    Cell(具体使用哪个类)
  • 为单元格赋值
  • 样式(单元格、字体、颜色、合并...)

以下附部分代码

/**
	 * 导出Excel 2007 OOXML (.xlsx)格式
	 * 
	 * @param title
	 *            标题行
	 * @param headMap
	 *            属性-列头
	 * @param jsonArray
	 *            数据集
	 * @param datePattern
	 *            日期格式,传null值则默认 年月日
	 * @param colWidth
	 *            列宽 默认 至少17个字节
	 * @param out
	 *            输出流
	 */
	public static void exportExcelX(String title, Map<String, String> headMap, JSONArray jsonArray, JSONArray jsonArray2, String datePattern, int colWidth, OutputStream out,
			List<CapitalFlow> inFlows, List<CapitalFlow> outFlows, List<BigDecimal> subtotalMap)
	{
		if (datePattern == null)
			datePattern = DEFAULT_DATE_PATTERN;
		// 声明一个工作薄
		SXSSFWorkbook workbook = new SXSSFWorkbook(1000);// 缓存
		workbook.setCompressTempFiles(true);
		// 表头样式
		CellStyle titleStyle = workbook.createCellStyle();
		titleStyle.setFillForegroundColor(HSSFColor.WHITE.index);
		titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		titleStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
		titleStyle.setAlignment(HorizontalAlignment.CENTER);
		Font titleFont = workbook.createFont();
		titleFont.setFontHeightInPoints((short) 20);
//		titleFont.setBoldweight((short) 700);
		titleStyle.setFont(titleFont);
		// 列头样式
		CellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setFillForegroundColor(HSSFColor.WHITE.index);
		headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		headerStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
		headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		headerStyle.setBorderBottom(BorderStyle.THIN);
		headerStyle.setBorderLeft(BorderStyle.THIN);
		headerStyle.setBorderRight(BorderStyle.THIN);
		headerStyle.setBorderTop(BorderStyle.THIN);
		headerStyle.setAlignment(HorizontalAlignment.CENTER);
		headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);

		Font headerFont = workbook.createFont();
		headerFont.setFontHeightInPoints((short) 12);
//		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headerFont.setBold(true);
		headerStyle.setFont(headerFont);
		// 单元格样式
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
		cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		cellStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
		cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		cellStyle.setBorderBottom(BorderStyle.THIN);
		cellStyle.setBorderLeft(BorderStyle.THIN);
		cellStyle.setBorderRight(BorderStyle.THIN);
		cellStyle.setBorderTop(BorderStyle.THIN);
		cellStyle.setAlignment(HorizontalAlignment.CENTER);
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		
		Font cellFont = workbook.createFont();
//		cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		cellFont.setBold(false);
		cellStyle.setFont(cellFont);
		// 生成一个(带标题)表格
		SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet();
		// 设置列宽
		int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;// 至少字节数
		int[] arrColWidth = new int[headMap.size()];
		// 产生表格标题行,以及设置列宽
		String[] properties = new String[headMap.size()];
		String[] headers = new String[headMap.size()];
		int ii = 0;
		for (Iterator<String> iter = headMap.keySet().iterator(); iter.hasNext();)
		{
			String fieldName = iter.next();

			properties[ii] = fieldName;
			headers[ii] = headMap.get(fieldName);

			int bytes = fieldName.getBytes().length;
			arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
			if (ii == 1)
			{
				sheet.setColumnWidth(ii, arrColWidth[ii] * 800);
			} else
			{
				sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
			}
			ii++;
		}
		// 遍历集合数据,产生数据行
		int rowIndex = 0;
		//  --汇总
		BigDecimal totalBefore = new BigDecimal(0);
		//  -----汇总
		BigDecimal totalIn = new BigDecimal(0);
		// -----汇总
		BigDecimal totalOut = new BigDecimal(0);
		// ----汇总
		BigDecimal totalToInOutSub = new BigDecimal(0);
		// ----汇总
		BigDecimal totalDayBalance = new BigDecimal(0);
		

			SXSSFRow titleRow = (SXSSFRow) sheet.createRow(0);// 表头
																// rowIndex=0
			titleRow.createCell(0).setCellValue(title);
			titleRow.getCell(0).setCellStyle(titleStyle);
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));

			SXSSFRow headerRow = (SXSSFRow) sheet.createRow(1); // 列头
																// rowIndex
																// =1
			for (int i = 0; i < headers.length; i++)
			{
				headerRow.createCell(i).setCellValue(headers[i]);
				headerRow.getCell(i).setCellStyle(headerStyle);

			}
			rowIndex = 2;// 数据内容从 rowIndex=2开始
		
	
		for (Object obj : jsonArray)
		{

		
			JSONObject jo = (JSONObject) JSONObject.toJSON(obj);

			totalBefore = totalBefore.add(jo.getBigDecimal("befforeDayBalance") == null ? new BigDecimal(0) : jo.getBigDecimal("befforeDayBalance"));
			totalIn = totalIn.add(jo.getBigDecimal("thisDayInflow") == null ? new BigDecimal(0) : jo.getBigDecimal("thisDayInflow"));
			totalOut = totalOut.add(jo.getBigDecimal("thisDayOutflow") == null ? new BigDecimal(0) : jo.getBigDecimal("thisDayOutflow"));
			totalToInOutSub = totalToInOutSub.add(jo.getBigDecimal("toInOutSub") == null ? new BigDecimal(0) : jo.getBigDecimal("toInOutSub"));
			totalDayBalance = totalDayBalance.add(jo.getBigDecimal("thisDayBalance") == null ? new BigDecimal(0) : jo.getBigDecimal("thisDayBalance"));
			SXSSFRow dataRow = (SXSSFRow) sheet.createRow(rowIndex);
			for (int i = 0; i < properties.length; i++)
			{
				SXSSFCell newCell = (SXSSFCell) dataRow.createCell(i);
				Object o = jo.get(properties[i]);
				String cellValue = "";
				if (o == null)
					cellValue = "";
				else if (o instanceof Date)
					cellValue = new SimpleDateFormat(datePattern).format(o);
				else if (o instanceof Float || o instanceof Double || o instanceof BigDecimal)
					cellValue = formatMoney(new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
				else
					cellValue = o.toString();
				if(cellValue.equals("0.00")) {
					newCell.setCellValue("");
				}else {
					newCell.setCellValue(cellValue);
				}
				newCell.setCellStyle(cellStyle);
				// 如果是第一列,那么合并单元格
				if (i == 0)
				{
//					// 合并单元格
					newCell.setCellValue("银行");
					newCell.setCellStyle(headerStyle);
				}
			}
			rowIndex++;
		}
		sheet.addMergedRegion(new CellRangeAddress(2, jsonArray.size() + 2, 0, 0));
		
		// 创建求和列
		SXSSFRow sumRow = (SXSSFRow) sheet.createRow(rowIndex);
		sumRow.createCell(0).setCellValue("");
		sumRow.getCell(0).setCellStyle(cellStyle);
		sumRow.createCell(1).setCellValue("存款小计");
		sumRow.getCell(1).setCellStyle(headerStyle);
		sumRow.createCell(2).setCellValue(formatMoney(totalBefore.setScale(2, BigDecimal.ROUND_HALF_UP)));
		sumRow.getCell(2).setCellStyle(headerStyle);
		sumRow.createCell(3).setCellValue(formatMoney(totalIn.setScale(2, BigDecimal.ROUND_HALF_UP)));
		sumRow.getCell(3).setCellStyle(headerStyle);
		sumRow.createCell(4).setCellValue(formatMoney(totalOut.setScale(2, BigDecimal.ROUND_HALF_UP)));
		sumRow.getCell(4).setCellStyle(headerStyle);
		sumRow.createCell(5).setCellValue(formatMoney(totalToInOutSub.setScale(2, BigDecimal.ROUND_HALF_UP)));
		sumRow.getCell(5).setCellStyle(headerStyle);
		sumRow.createCell(6).setCellValue(formatMoney(totalDayBalance.setScale(2, BigDecimal.ROUND_HALF_UP)));
		sumRow.getCell(6).setCellStyle(headerStyle);

		// 生成一行后,行标识自动加1
		rowIndex++;
		//现金数据
		for (Object obj : jsonArray2)
		{
			JSONObject jo = (JSONObject) JSONObject.toJSON(obj);

//			totalBeforeMoney = totalBeforeMoney.add(jo.getBigDecimal("befforeDayBalance") == null ? new BigDecimal(0) : jo.getBigDecimal("befforeDayBalance"));
//			totalInMoney = totalIn.add(jo.getBigDecimal("thisDayInflow") == null ? new BigDecimal(0) : jo.getBigDecimal("thisDayInflow"));
//			totalOutMoney = totalOut.add(jo.getBigDecimal("thisDayOutflow") == null ? new BigDecimal(0) : jo.getBigDecimal("thisDayOutflow"));
//			totalToInOutSubMoney = totalToInOutSub.add(jo.getBigDecimal("toInOutSub") == null ? new BigDecimal(0) : jo.getBigDecimal("toInOutSub"));
//			totalDayBalanceMoney = totalDayBalance.add(jo.getBigDecimal("thisDayBalance") == null ? new BigDecimal(0) : jo.getBigDecimal("thisDayBalance"));
			SXSSFRow dataRow = (SXSSFRow) sheet.createRow(rowIndex);
			for (int i = 0; i < properties.length; i++)
			{
				SXSSFCell newCell = (SXSSFCell) dataRow.createCell(i);
				Object o = jo.get(properties[i]);
				String cellValue = "";
				if (o == null)
					cellValue = "";
				else if (o instanceof Date)
					cellValue = new SimpleDateFormat(datePattern).format(o);
				else if (o instanceof Float || o instanceof Double || o instanceof BigDecimal)
					cellValue = formatMoney(new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
				else
					cellValue = o.toString();
				if(cellValue.equals("0.00")) {
					newCell.setCellValue("");
				}else {
					newCell.setCellValue(cellValue);
				}
				newCell.setCellStyle(cellStyle);
				// 如果是第一列,那么合并单元格
				if (i == 0)
				{
//					// 合并单元格
					newCell.setCellValue("现金");
					newCell.setCellStyle(headerStyle);
				}
			}
			rowIndex++;
		}
		// ----------------------现金小计----------------------
		for (int k = 0; k < 1; k++)
		{
			SXSSFRow cashRow = (SXSSFRow) sheet.createRow(rowIndex);
			for (int i = 0; i < properties.length; i++)
			{
				SXSSFCell newCell = (SXSSFCell) cashRow.createCell(i);
				String cellValue = "";
				if (i == 0 && k == 0)
				{
					cellValue = "现金";
					newCell.setCellStyle(headerStyle);
					// 合并单元格
//					sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex + 2, 0, 0));
				}
				if (i == 1 && k == 0)
				{
					cellValue = "现金小计";
					newCell.setCellStyle(headerStyle);
				}
				if (i == 2 && k == 0)
				{
					cellValue = formatMoney(subtotalMap.get(0));
					newCell.setCellStyle(headerStyle);
				}
				if (i == 3 && k == 0)
				{
					cellValue = formatMoney(subtotalMap.get(1));
					newCell.setCellStyle(headerStyle);
				}
				if (i == 4 && k == 0)
				{
					cellValue = formatMoney(subtotalMap.get(2));
					newCell.setCellStyle(headerStyle);
				}
				if (i == 5 && k == 0)
				{
					cellValue = formatMoney(subtotalMap.get(3));
					newCell.setCellStyle(headerStyle);
				}
				if (i == 6 && k == 0)
				{
					cellValue = formatMoney(subtotalMap.get(4));
					newCell.setCellStyle(headerStyle);
				}

				newCell.setCellValue(cellValue);

			}
			rowIndex++;
		}
		sheet.addMergedRegion(new CellRangeAddress(jsonArray.size() + 3, jsonArray.size() + jsonArray2.size() + 3, 0, 0));
		
		// ---------------合计----------------------------------------
		SXSSFRow totalRow = (SXSSFRow) sheet.createRow(rowIndex);
		totalRow.createCell(0).setCellValue("合计");
		totalRow.getCell(0).setCellStyle(headerStyle);
		totalRow.createCell(1).setCellValue("合计");
		totalRow.getCell(1).setCellStyle(headerStyle);
		totalRow.createCell(2).setCellValue(formatMoney((totalBefore.add(subtotalMap.get(0))) .setScale(2, BigDecimal.ROUND_HALF_UP)));
		totalRow.getCell(2).setCellStyle(headerStyle);
		totalRow.createCell(3).setCellValue(formatMoney(totalIn.add(subtotalMap.get(1)).setScale(2, BigDecimal.ROUND_HALF_UP)));
		totalRow.getCell(3).setCellStyle(headerStyle);
		totalRow.createCell(4).setCellValue(formatMoney(totalOut.add(subtotalMap.get(2)).setScale(2, BigDecimal.ROUND_HALF_UP)));
		totalRow.getCell(4).setCellStyle(headerStyle);
		totalRow.createCell(5).setCellValue(formatMoney(totalToInOutSub.add(subtotalMap.get(3)).setScale(2, BigDecimal.ROUND_HALF_UP)));
		totalRow.getCell(5).setCellStyle(headerStyle);
		totalRow.createCell(6).setCellValue(formatMoney(totalDayBalance.add(subtotalMap.get(4)).setScale(2, BigDecimal.ROUND_HALF_UP)));
		totalRow.getCell(6).setCellStyle(headerStyle);
		rowIndex++;

		// ----------------------------资金 流入 ******流出
		int inCount = inFlows.size();
		int outCount = outFlows.size();
		int compareCount = inCount - outCount;
		int rowCount = 0;
		// 收入 -----汇总
		BigDecimal totalDailyIn = new BigDecimal(0);

		// 支出-----汇总
		BigDecimal totalDailyOut = new BigDecimal(0);
		// 如果流入的数据 多于流出的数据 那么以流入的数量 为标准生成 否则以流出为标准
		if (compareCount > 0)
		{
			rowCount = inCount;
		} else
		{
			rowCount = outCount;
		}
		// 生成 首列明
		SXSSFRow firstHeadRow = (SXSSFRow) sheet.createRow(rowIndex);
		firstHeadRow.createCell(0).setCellValue("");
		firstHeadRow.getCell(0).setCellStyle(cellStyle);
		firstHeadRow.createCell(1).setCellValue("摘要");
		firstHeadRow.getCell(1).setCellStyle(headerStyle);
		firstHeadRow.createCell(2).setCellValue("金  额");
		firstHeadRow.getCell(2).setCellStyle(headerStyle);
		firstHeadRow.createCell(3).setCellValue("");
		firstHeadRow.getCell(3).setCellStyle(headerStyle);
		firstHeadRow.createCell(4).setCellValue("摘要");
		firstHeadRow.getCell(4).setCellStyle(headerStyle);
		CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, 4, 5);
		sheet.addMergedRegion(cra);
		//合并单元格并设置边框
		setRegionBorder(1, cra, sheet, workbook);
//		sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 4, 5));
		// 合并列

		// firstHeadRow.createCell(5).setCellValue();
		// firstHeadRow.getCell(5).setCellStyle(headerStyle);
		firstHeadRow.createCell(6).setCellValue("金 额");
		firstHeadRow.getCell(6).setCellStyle(headerStyle);
		rowIndex++;
		for (int k = 0; k < rowCount; k++)
		{
			SXSSFRow inOutRow = (SXSSFRow) sheet.createRow(rowIndex);
			for (int i = 0; i < 7; i++)
			{
				SXSSFCell newCell = (SXSSFCell) inOutRow.createCell(i);
				String cellValue = "";
				if (i == 0 && k == 0)
				{
					cellValue = "收入明细";
					newCell.setCellValue(cellValue);
					// 合并单元格
					newCell.setCellStyle(headerStyle);
					sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex + rowCount, 0, 0));
				}
				if (i == 1)
				{
					if (k > inCount - 1)
					{
						cellValue = "";
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
					} else
					{
						cellValue = inFlows.get(k).getBusinessSummary();
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
					}
				}

				if (i == 2)
				{
					if (k > inCount - 1)
					{
						cellValue = "";
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
					} else
					{
						if(null!=inFlows.get(k)&&null!=inFlows.get(k).getAmountExecute()){
						totalDailyIn = totalDailyIn.add(inFlows.get(k).getAmountExecute());
						cellValue = formatMoney(inFlows.get(k).getAmountExecute().setScale(2, BigDecimal.ROUND_HALF_UP));
						System.err.println(cellValue);
//						for(CapitalFlow capitalFlow : inFlows) {
//							System.err.println(capitalFlow.toString());
//						}
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
						}
						
					}

				}

				if (i == 3 && k == 0)
				{
					cellValue = "支出明细";
					// 合并单元格
					sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex + rowCount, 3, 3));
					newCell.setCellValue(cellValue);
					newCell.setCellStyle(headerStyle);
				}
				if (i == 4)
				{
					if (k > outCount - 1)
					{
						cellValue = "";
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
					} else
					{
						cellValue = outFlows.get(k).getBusinessSummary();
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
					}
//					sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 4, 5));

				}
				if (i == 5) {
					cellValue = "";
					newCell.setCellValue(cellValue);
					newCell.setCellStyle(cellStyle);
					CellRangeAddress cra2 = new CellRangeAddress(rowIndex, rowIndex, 4, 5);
					sheet.addMergedRegion(cra2);
					//合并单元格并设置边框
					setRegionBorder(1, cra2, sheet, workbook);
				}
				if (i == 6)
				{
					if (k > outCount - 1)
					{
						cellValue = "";
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
					} else
					{
						if(null!=outFlows.get(k)&&null!=outFlows.get(k).getAmountExecute())
						{
						totalDailyOut = totalDailyOut.add(outFlows.get(k).getAmountExecute());
						cellValue = formatMoney(outFlows.get(k).getAmountExecute().setScale(2, BigDecimal.ROUND_HALF_UP));
						newCell.setCellValue(cellValue);
						newCell.setCellStyle(cellStyle);
						}
					}

				}

			}
			rowIndex++;
		}
		// 日计 求和
		SXSSFRow sumDailyRow = (SXSSFRow) sheet.createRow(rowIndex);
		sumDailyRow.createCell(0).setCellValue("");
		sumDailyRow.getCell(0).setCellStyle(cellStyle);
		sumDailyRow.createCell(1).setCellValue("日    计");
		sumDailyRow.getCell(1).setCellStyle(headerStyle);
		sumDailyRow.createCell(2).setCellValue(formatMoney(totalDailyIn.setScale(2, BigDecimal.ROUND_HALF_UP)));
		sumDailyRow.getCell(2).setCellStyle(headerStyle);
		sumDailyRow.createCell(3).setCellValue("");
		sumDailyRow.getCell(3).setCellStyle(headerStyle);
		sumDailyRow.createCell(4).setCellValue("日    计");
		sumDailyRow.getCell(4).setCellStyle(headerStyle);
		CellRangeAddress cra3 = new CellRangeAddress(rowIndex, rowIndex, 4, 5);
		sheet.addMergedRegion(cra3);
		//合并单元格并设置边框
		setRegionBorder(1, cra3, sheet, workbook);
//		sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 4, 5));
		// 合并列

		sumDailyRow.createCell(6).setCellValue(formatMoney(totalDailyOut.setScale(2, BigDecimal.ROUND_HALF_UP)));
		sumDailyRow.getCell(6).setCellStyle(headerStyle);
		rowIndex++;

		// 自动调整宽度
		/*
		 * for (int i = 0; i < headers.length; i++) { sheet.autoSizeColumn(i); }
		 */
		try
		{
			workbook.write(out);
			 workbook.close();
			workbook.dispose();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

3、问题

    a、数据格式化

private static String formatMoney(BigDecimal decimal) {
		if (decimal == null) {
			return new StringBuilder("").append(new DecimalFormat("###,###,###,##0.00").format(BigDecimal.ZERO)).toString();
		} else {
			return new StringBuilder("").append(new DecimalFormat("###,###,###,##0.00").format(decimal)).toString();
		}
	}

    b、合并单元格的两种方式

Ⅰ、new CellRangeAddress
sheet.addMergedRegion(new CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol;
参数:起始行号,终止行号, 起始列号,终止列号

Ⅱ、new Range(a,b,c,d)
    弃用

    c、合并单元格后边框不显示

/**
     * @param border 边框宽度
     * @param region 合并单元格区域范围
     * @param sheet  
     * @param wb
     */
    public static void setRegionBorder(int border, CellRangeAddress region, Sheet sheet,Workbook wb){  
        RegionUtil.setBorderBottom(border,region, sheet);  
        RegionUtil.setBorderLeft(border,region, sheet);  
        RegionUtil.setBorderRight(border,region, sheet);  
        RegionUtil.setBorderTop(border,region, sheet);         
    } 

4. 工具

    数据相同时合并行

//根据需要自定义开始行、结束行的初始化
                int first = 3;
		int last = 4;
		lable :for(int i = 3; i < sheet.getLastRowNum() - 1; i++) {
			for(int j = i + 1; j < sheet.getLastRowNum(); j++) {
					SXSSFRow firstRangRow = sheet.getRow(i);
					SXSSFCell firstRangCell = (SXSSFCell) firstRangRow.getCell(0);
					SXSSFRow lastRangRow = sheet.getRow(j);
					SXSSFCell lastRangCell = (SXSSFCell) lastRangRow.getCell(0);
					if(firstRangCell.getStringCellValue().equals(lastRangCell.getStringCellValue())){
						last = j;
						if((last+1) == sheet.getLastRowNum()) {
							try {
								sheet.addMergedRegion(new CellRangeAddress(first, last+1, 0, 0));
								break lable;
							}catch (Exception e) {
								e.printStackTrace();
							}
						}
					}else {
						try {
							sheet.addMergedRegion(new CellRangeAddress(first, last, 0, 0));
						}catch (Exception e) {
							e.printStackTrace();
						}
						
						first = last + 1;
						i = last;
						continue lable;
					}
			}
		}

 

后续问题继续更新!

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值