ReportUtils.java 14 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
package com.bsth.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;

import com.bsth.entity.Line;
import com.bsth.entity.realcontrol.ScheduleRealInfo;

public class ReportUtils {
	// private final String packaegName = "com.bsth.entity.";
	private final String packaegName = "com.bsth.entity.realcontrol.";

	/**
	 * /**
	 * 
	 * @param list
	 *            模板中,需要重复显示的行所需的数据
	 * @param map
	 *            模板中除以上list外所有的数据
	 * @param index
	 *            需要重复的行号,该值为行号减1
	 * @param sourcePath
	 *            模板路径
	 * @param targetPath
	 *            生成路径
	 */
	public void excelReplace(List<Iterator<?>> list, Object[] tArray,
			String sourcePath, String targetPath) {
		try {
			// 把源文件放入流中
			POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
					sourcePath));
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			HSSFSheet sheet = wb.getSheetAt(0);
			HSSFRow row;
			HSSFCell cell = null;
			String key;
			// 取得总行数
			int rowNum = sheet.getLastRowNum();
			// 取得总列数
			int cellNum = sheet.getRow(0).getLastCellNum();

			// 遍历行
			for (int i = 0; i < rowNum; i++) {
				row = sheet.getRow(i);
				// 遍历列
				for (int j = 0; j < cellNum; j++) {
					if (row == null) {
						continue;
					}
					cell = row.getCell(j);
					if (cell == null) {
						continue;
					}
					// 取得每列的内容,如果列内容是$key$格式,则替换内容
					key = getCellValue(cell);
					if (key != null && (key.indexOf("$") != -1 || key.indexOf("#list#") != -1)) {
						// * 列中内容有#list#,则表示该行为模板行,需要以该行为模板
						// * 例如:模板行格式 #list#0_0 $Car.id$
						// * 第一个0表示需要在list中取iterator的索引值
						// * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
						// * $Car.id$表示所取的对象为Car的对象,并且取值为id的值
						if (key.indexOf("#list#") != -1) {
							key = key.replace("#list#", "").trim();
							String[] lists = key.split(" ");
							// 取得list中的索引值
							int listIndex = Integer
									.valueOf(lists[0].split("_")[0]);
							Iterator<?> iterator = list.get(listIndex);
							// 根据模板创建行并填弃数据,返回增加的行数
							int rowCount = iteratorFillCellValue(wb, sheet,
									cell, iterator, i, rowNum, key);
							rowNum += rowCount;
							i += rowCount;
							break;
						} else {
							// 直接填充数据的列,从对象数组中取得值,这里的数组不传值
							getValueAndSetCellValue(cell, key, tArray, new String[]{""});
						}
					}

				}
			}
			// 创建目标文件夹
			createFolder(targetPath);
			// 输出文件
			FileOutputStream fileOut = new FileOutputStream(targetPath);
			wb.write(fileOut);
			fileOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getCellValue(HSSFCell cell) {
		int cellType = 0;
		String result = "";
		double d;
		if(cell != null) {
			// 获取列数据类型
			cellType = cell.getCellType();
			// 不同列数据类型,取值方法不同
			switch(cellType) {
				// String
				case HSSFCell.CELL_TYPE_STRING:
					result = cell.getStringCellValue().toString();
					break;
				// numeric类型,excel中,日期格式会转成数字格式存储
				case HSSFCell.CELL_TYPE_NUMERIC:
					result = cell.getNumericCellValue()+"";
					break;
				// 公式类型
				case HSSFCell.CELL_TYPE_FORMULA:
					result = cell.getCellFormula() + "";
					break;
				// boolean类型
				case HSSFCell.CELL_TYPE_BOOLEAN:
					result = cell.getBooleanCellValue() + "";
					break;
				// 空格
				case HSSFCell.CELL_TYPE_BLANK:
					result = null;
					break;
				// 错误值
				case HSSFCell.CELL_TYPE_ERROR:
					result = null;
					break;
				default :
					System.out.println("其它");
					break;
			}
		}
		return result;
	}
	
	/**
	 * 根据iterator,以及模板中的标识,填充模板
	 * 
	 * @param wb
	 * @param sheet
	 * @param cell
	 * @param iterator
	 *            iterator
	 * @param index
	 *            模板行索引
	 * @param rowNum
	 *            表格总行数
	 * @param key
	 *            表格内容
	 * @return
	 */
	private int iteratorFillCellValue(HSSFWorkbook wb, HSSFSheet sheet,
			HSSFCell cell, Iterator<?> iterator, int index, int rowNum,
			String key) {
		int rowCount = 0;
		Object obj = null;
		int p = 0;
		int i = index;
		HSSFRow newRow = null;
		int tmpCellNum = 0;
		int k = 0;
		int listIndex = 0;
		// 取得模板行
		HSSFRow orgRow = sheet.getRow(index);
		try {
			while (iterator.hasNext()) {
				// 取得iterator的对象
				obj = iterator.next();
				// 移动当前编辑行以下的所有行
				if (p != 0) {
					rowNum += 1;
					i += 1;
					rowCount += 1;// 增加的总行数
					// 把当前行以下的所有行往下移动1行
					sheet.shiftRows(i, rowNum, 1);
				}
				p = 1;
				// 创建新行
				newRow = sheet.createRow(index + k++);
				// 把新行的内容换成和模板行一样
				copyRow(wb, orgRow, newRow, true);
				tmpCellNum = newRow.getLastCellNum();
				for (int l = 0; l < tmpCellNum; l++) {
					cell = newRow.getCell(l);
					key = getCellValue(cell);
					/**
					 * 如果单无格内容为#list#,表示该行是模板行 #list#0_0
					 * 第一个0表示需要在list中取iterator的索引值
					 * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
					 */
					if (key.indexOf("#list#") != -1 && key.indexOf("_0") == -1) {
						if (iterator.hasNext()) {
							obj = iterator.next();
						} else {
							obj = null;
						}
					}
					if (key.trim().indexOf(" ") != -1) {
						key = key.split(" ")[1];
					}
					getValueAndSetCellValue(cell, key, obj,new String[]{listIndex+""});
				}
				// list的数量
				listIndex ++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rowCount;
	}

	/**
	 * 取到相应的值并填入相应的列中
	 * 
	 * @param cell  列
	 * @param key 列内容
	 * @param obj 数据源对象
	 * @param args 其他参数 数组
	 * 数组内容:
	 * 0位:在list中的第几条数据
	 */
	private void getValueAndSetCellValue(HSSFCell cell, String key, Object obj, String[] args) {
		try {
			// 保有存单元格的内容
			String cellValue = key = key.replace("\\n", "");
			String tmpKey;
			// 判断单元格内容是否是公式
			if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
				Pattern p=Pattern.compile("(\\d+)");  //  
				Matcher m=p.matcher(key); 
				if(m.find()){
					cellValue = key.replace(m.group(1), 
							Integer.valueOf(m.group(1))+Integer.valueOf(args[0])+"");
					cell.setCellFormula(cellValue);
					return;
				} 
			}else{//其他格式
				
				// 循环截取两个$中间的内容,反射出值
				while (key.indexOf("$") != -1) {
					key = key.substring(key.indexOf("$") + 1);
					// 取两个$中间的内容
					tmpKey = key.substring(0, key.indexOf("$"));
					key = key.substring(key.indexOf("$") + 1);
					// 如果内容是如下格式Cars.id,则从obj中值得相应的对象的值
					if (tmpKey.indexOf(".") != -1) {
						String className = tmpKey.substring(0, tmpKey.indexOf("."));
						// 取得类的全限定名
						String classWholeName = packaegName + className;
						String fieldName = tmpKey.substring(tmpKey.indexOf(".") + 1);
						// 如果obj是数组,循环判断哪个对象是对应的
						if (obj instanceof Object[]) {
							Object[] objs = (Object[]) obj;
							for (int k = 0; k < objs.length; k++) {
								if (objs[k].getClass().getName().equals(classWholeName)) {
									cellValue = cellValue.replace("$" + tmpKey
											+ "$", getKeyValue(objs[k], fieldName)
											+ "");
								} else if(objs[k].getClass().getName().equals("java.util.HashMap")){
									Map<String,Object> map = (HashMap<String,Object>)objs[k];
									cellValue = cellValue.replace("$" + tmpKey + "$",map.get(fieldName)+"");
								}
							}
						} else if (obj.getClass().getName().equals(classWholeName)) {
							cellValue = cellValue.replace("$" + tmpKey + "$",getKeyValue(obj, fieldName) + "");
						}
					}
				}
			}
			cell.setCellValue(cellValue);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 给列填充数据
	 * 
	 * @param cell
	 *            列
	 * @param obj
	 *            数据源对象
	 * @param fieldName
	 *            需要取数据的字段
	 */
	private Object getKeyValue(Object obj, String fieldName) {
		Object value = "";
		try {
			if (obj != null) {
				ReportRelatedUtils test = new ReportRelatedUtils();
				value = test.getValue(obj, fieldName) == null ? "" : test .getValue(obj, fieldName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	public static void main(String[] args) {

		try {
			ReportUtils ee = new ReportUtils();
			List<Iterator<?>> list = new ArrayList<Iterator<?>>();
			Line line = new Line();
			line.setId(1);
			line.setName("line1");

			List<Object> dataList = new ArrayList<Object>();
			

			ScheduleRealInfo srr = new ScheduleRealInfo();
			srr.setId((long) 111);
			srr.setXlName("abc11");
			
			ScheduleRealInfo sr = new ScheduleRealInfo();
			sr.setZdsj("06:10");
			sr.setZdsjActual("06:25");
			dataList.add(sr);
			sr = new ScheduleRealInfo();
			sr.setZdsj("06:20");
			sr.setZdsjActual("");
			dataList.add(sr);
			list.add(dataList.iterator());
			
			ee.excelReplace(list, new Object[] { srr }, "D:\\waybill.xls",
					"D:\\22.xls");
			System.out.println("ok");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 行复制功能
	 * 
	 * @param fromRow
	 * @param toRow
	 */
	private void copyRow(HSSFWorkbook wb, HSSFRow fromRow, HSSFRow toRow,
			boolean copyValueFlag) {
		for (Iterator<Cell> cellIt = fromRow.cellIterator(); cellIt.hasNext();) {
			HSSFCell tmpCell = (HSSFCell) cellIt.next();
			HSSFCell newCell = toRow.createCell(tmpCell.getColumnIndex(), 0);
			copyCell(wb, tmpCell, newCell, copyValueFlag);
		}
	}

	/**
	 * 复制单元格
	 * 
	 * @param srcCell
	 * @param distCell
	 * @param copyValueFlag
	 *            true则连同cell的内容一起复制
	 */
	public void copyCell(HSSFWorkbook wb, HSSFCell srcCell, HSSFCell distCell,
			boolean copyValueFlag) {
		HSSFCellStyle newstyle = wb.createCellStyle();
		copyCellStyle(wb, srcCell.getCellStyle(), newstyle);
		// 样式
		distCell.setCellStyle(newstyle);
		// 评论
		if (srcCell.getCellComment() != null) {
			distCell.setCellComment(srcCell.getCellComment());
		}
		// 不同数据类型处理
		int srcCellType = srcCell.getCellType();
		distCell.setCellType(srcCellType);
		if (copyValueFlag) {
			if (srcCellType == HSSFCell.CELL_TYPE_NUMERIC) {
				distCell.setCellValue(srcCell.getDateCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_STRING) {
				distCell.setCellValue(srcCell.getRichStringCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_BLANK) {

			} else if (srcCellType == HSSFCell.CELL_TYPE_BOOLEAN) {
				distCell.setCellValue(srcCell.getBooleanCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_ERROR) {
				distCell.setCellErrorValue(srcCell.getErrorCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_FORMULA) {
				distCell.setCellFormula(srcCell.getCellFormula());
			} else {
			}
		}
	}

	/**
	 * 复制一个单元格样式到目的单元格样式
	 * 
	 * @param fromStyle
	 * @param toStyle
	 */
	public void copyCellStyle(HSSFWorkbook wb, HSSFCellStyle fromStyle,
			HSSFCellStyle toStyle) {
		toStyle.setAlignment(fromStyle.getAlignment());
		// 边框和边框颜色
		toStyle.setBorderBottom(fromStyle.getBorderBottom());
		toStyle.setBorderLeft(fromStyle.getBorderLeft());
		toStyle.setBorderRight(fromStyle.getBorderRight());
		toStyle.setBorderTop(fromStyle.getBorderTop());
		toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
		toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
		toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
		toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());

		// 背景和前景
		toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
		toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());

		toStyle.setDataFormat(fromStyle.getDataFormat());
		toStyle.setFillPattern(fromStyle.getFillPattern());
		toStyle.setHidden(fromStyle.getHidden());
		toStyle.setIndention(fromStyle.getIndention());// 首行缩进
		toStyle.setLocked(fromStyle.getLocked());
		toStyle.setRotation(fromStyle.getRotation());// 旋转
		toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());
		toStyle.setWrapText(fromStyle.getWrapText());
		// 字体
		toStyle.setFont(fromStyle.getFont(wb));

	}

	/**
	 * 创建文件夹,并删除原有文件
	 * 
	 * @param path
	 */
	private void createFolder(String path) {
		File targetFile = null;
		targetFile = new File(path);
		if (targetFile.exists()) {// 删除原有文件
			targetFile.delete();
		}
		// 创建目标文件夹
		targetFile = new File(path.substring(0, path.lastIndexOf("\\")));
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
	}

}