Excel导出工具类 ExportUtil


/**
 * 生成excel表格
 * 
 * @author
 * 
 */
public class ExportUtil {

	/**
	 * 构造器
	 * 
	 */
	public ExportUtil() {
	}

	/**
	 * 生成具有一定格式excel
	 * 
	 * @param sheetName sheet名称,默认为sheet1
	 * @param nf 数字类型的格式 如:jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");默认无格式
	 * @param content 二维数组,要生成excel的数据来源
	 * @param 合并项 每一项的数据格式为0,1,0,2 即:把(0,1)和(0,2)合并--->第1列的第一、二个元素合并
	 * @param os excel输出流
	 * @param row 需要水平居中的行,默认居左。以逗号分隔的字符串
	 * @param col 需要水平居中的列,默认居左。以逗号分隔的字符串
	 */
	public void export(String sheetName, NumberFormat nf, String[][] content, String[] mergeInfo, OutputStream os,
			String row, String col) {
		if (VerifyUtil.isNullObject(content, os) || VerifyUtil.isNull2DArray(content)) {
			return;
		}
		// 默认名称
		if (VerifyUtil.isNullObject(sheetName)) {
			sheetName = "sheet1";
		}
		Set<Integer> rows = this.getInfo(row);
		Set<Integer> cols = this.getInfo(col);
		WritableWorkbook workbook = null;
		try {
			workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet(sheetName, 0);
			sheet.setColumnView(0, 20);
			for (int i = 0; i < content.length; i++) {
				for (int j = 0; j < content[i].length; j++) {
					if (content[i][j] == null) {
						content[i][j] = "";
					}
					if (isNumber(content[i][j]) && (!rows.contains(i) || !cols.contains(j))) {// 处理数字
						Number number = null;
						if (VerifyUtil.isNullObject(nf)) {// 数字无格式
							number = new Number(j, i, Double.valueOf(content[i][j]));
						} else {// 如果有格式,按格式生成
							jxl.write.WritableCellFormat wcfn = new jxl.write.WritableCellFormat(nf);
							number = new Number(j, i, Double.valueOf(content[i][j]), wcfn);
						}
						sheet.addCell(number);
					} else {// 处理非数字
						WritableCellFormat format = new WritableCellFormat();
						if (rows.contains(i) || cols.contains(j)) {
							format.setAlignment(jxl.format.Alignment.CENTRE);
						} else {
							format.setAlignment(jxl.format.Alignment.LEFT);
						}
						format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						Label label = new Label(j, i, content[i][j], format);
						sheet.addCell(label);
					}
				}
			}
			this.merge(sheet, mergeInfo);
			workbook.write();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workbook.close();
				os.close();
			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 生成固定格式的excel,表格都为文本,水平居左,垂直居中
	 * 
	 * @param sheetName sheet名称,默认为sheet1
	 * @param content 二维数组,要生成excel的数据来源
	 * @param os excel输出流
	 */
	public void exportFormatExcel(String[][] content, String sheetName, OutputStream os) {
		if (VerifyUtil.isNullObject(content, os) || VerifyUtil.isNull2DArray(content)) {
			return;
		}
		// 默认名称
		if (VerifyUtil.isNullObject(sheetName)) {
			sheetName = "sheet1";
		}
		WritableWorkbook workbook = null;
		try {
			workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet(sheetName, 0);
			for (int i = 0; i < content.length; i++) {
				for (int j = 0; j < content[i].length; j++) {
					if (content[i][j] == null) {
						content[i][j] = "";
					}
					WritableCellFormat format = new WritableCellFormat();
					format.setAlignment(jxl.format.Alignment.LEFT);
					format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
					Label label = new Label(j, i, content[i][j], format);
					sheet.addCell(label);
				}
			}
			workbook.write();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workbook.close();
			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 生成固定格式的excel,表格都为文本,水平居左,垂直居中
	 * 
	 * @param sheetName sheet名称,默认为sheet1
	 * @param content Map,要生成excel的数据来源
	 * @param os excel输出流
	 */
	public void exportFormatExcel(Map<String, String[][]> content, String[] salary_name_array, String sheetName,
			OutputStream os) {
		if (VerifyUtil.isNullObject(content, os) || content.size() == 0) {
			return;
		}
		// 默认名称
		if (VerifyUtil.isNullObject(sheetName)) {
			sheetName = "sheet1";
		}
		WritableWorkbook workbook = null;
		try {
			workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet(sheetName, 0);
			int index = 0;
			for (int k = 0; k < salary_name_array.length; k++) {
				String[][] value = (String[][]) content.get(salary_name_array[k]);
				if (value != null && value.length > 0) {
					if (index != 0) {
						index++;
					}
					WritableCellFormat format1 = new WritableCellFormat();
					format1.setAlignment(jxl.format.Alignment.LEFT);
					format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
					Label label1 = new Label(0, index, salary_name_array[k], format1);
					sheet.addCell(label1);
					for (int i = 0; i < value.length; i++) {
						index++;
						for (int j = 0; j < value[i].length; j++) {
							if (value[i][j] == null) {
								value[i][j] = "";
							}
							WritableCellFormat format = new WritableCellFormat();
							format.setAlignment(jxl.format.Alignment.LEFT);
							format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
							Label label = new Label(j, index, value[i][j], format);
							sheet.addCell(label);
						}
					}
				}
			}
			workbook.write();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workbook.close();
			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 生成固定格式包含图片的 的excel,表格都为文本,水平居左,垂直居中,图片在表格下
	 * 
	 * @param sheetName sheet名称,默认为sheet1
	 * @param content 二维数组,要生成excel的数据来源
	 * @param os excel输出流
	 * @param image64 转成base64编码格式字符串 的 图片
	 */
	public void exportInCludeImageExcel(String[][] content, String sheetName, String image64, OutputStream os) {
		if (VerifyUtil.isNullObject(content, os) || VerifyUtil.isNull2DArray(content)) {
			return;
		}
		// 默认名称
		if (VerifyUtil.isNullObject(sheetName)) {
			sheetName = "sheet1";
		}
		WritableWorkbook workbook = null;
		try {
			workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet(sheetName, 0);
			for (int i = 0; i < content.length; i++) {
				for (int j = 0; j < content[i].length; j++) {
					if (content[i][j] == null) {
						content[i][j] = "";
					}
					WritableCellFormat format = new WritableCellFormat();
					format.setAlignment(jxl.format.Alignment.LEFT);
					format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
					Label label = new Label(j, i, content[i][j], format);
					sheet.addCell(label);
				}
			}
			File imgFile = null;
			if (image64.length() > 0) {
				BASE64Decoder decoder = new BASE64Decoder();
				byte[] bytes = decoder.decodeBuffer(image64.split(",")[1]);
				for (int i = 0; i < bytes.length; ++i) {
					if (bytes[i] < 0) {
						bytes[i] += 256;
					}
				}
				imgFile = new File(Local.getLocalSpace().getUserTempSpace(Local.getCompanyid(), Local.getUserid()),
						PrimaryCode.getUUID() + ".png");
				OutputStream out = new FileOutputStream(imgFile);
				out.write(bytes);
				out.flush();
				out.close();
				int i = 0;
				if (content[0].length > 10 && content[0].length < 20) {
					i = content[0].length;
				} else if (content[0].length > 20) {
					i = 19;
				} else {
					i = 10;
				}
				WritableImage image = new WritableImage(0, content.length, i, 23, imgFile);
				sheet.addImage(image);
			}
			workbook.write();
			if (imgFile != null) imgFile.delete();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workbook.close();
			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 合并表格
	 * 
	 * @param sheet 工作表
	 * @param mergeInfo 要合并的表格的信息
	 * @throws RowsExceededException
	 * @throws NumberFormatException
	 * @throws WriteException
	 */
	private void merge(WritableSheet sheet, String[] mergeInfo)
			throws RowsExceededException, NumberFormatException, WriteException {
		if (VerifyUtil.isNullObject(sheet) || VerifyUtil.isNull1DArray(mergeInfo)) {
			return;
		} else if (!this.isMergeInfo(mergeInfo)) {
			return;
		} else {
			for (String str : mergeInfo) {
				String[] temp = str.split(",");
				sheet.mergeCells(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Integer.parseInt(temp[2]),
						Integer.parseInt(temp[3]));
			}
		}
	}

	/**
	 * 处理要居中的行或列的数据
	 * 
	 * @param indexes 行标或列标
	 * @return 行坐标或列坐标组成的集合
	 */
	private Set<Integer> getInfo(String indexes) {
		Set<Integer> set = new HashSet<Integer>();
		if (VerifyUtil.isNullObject(indexes)) {
			return set;
		}
		String[] temp = indexes.split(",", 0);
		for (String str : temp) {
			if (isNumeric(str)) {
				set.add(Integer.parseInt(str));
			}
		}
		return set;
	}

	/**
	 * 判断字符串是否由纯数字组成
	 * 
	 * @param str 源字符串
	 * @return true是,false否
	 */
	private boolean isNumeric(String str) {
		if (VerifyUtil.isNullObject(str)) {
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str 源字符串
	 * @return true是,false否
	 */
	private boolean isNumber(String number) {
		boolean isnum = NumberUtils.isNumber(number);
		return isnum;
	}

	/**
	 * 判断合并项内容是否合法
	 * 
	 * @param mergeInfo 合并项 每一项的数据格式为0,1,0,2即把(0,1)和(0,2)合并
	 * @return true合法,false非法
	 */
	private boolean isMergeInfo(String[] mergeInfo) {
		if (VerifyUtil.isNull1DArray(mergeInfo)) {
			return false;
		} else {
			for (String str : mergeInfo) {
				String[] temp = str.split(",");
				if (VerifyUtil.isNull1DArray(temp) || temp.length != 4) {
					return false;
				} else {
					for (String s : temp) {
						if (!isNumeric(s)) {
							return false;
						}
					}
				}
			}
		}
		return true;
	}

	public static void main(String[] args) {
		ExportUtil ee = new ExportUtil();
		String[][] content = new String[][] { { "", "第一列", null, "第三列" }, { "第一行", "aa", "2.00", "22" },
				{ "第二行", "bb", "3.01", "32" }, { "第三行", "cc", "4.00", "41" } };
		try {
			OutputStream os = new FileOutputStream("D:/test2.xls");
			ee.export(null, null, content, new String[] { "0,1,0,2", "1,0,3,0" }, os, "0,1", "0");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java Excel 导出工具类的示例,可以使用 Apache POI 库来实现: ```java import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExportUtil { public static void export(List<Object[]> data, String[] headers, String sheetName, String filePath) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(sheetName); // 设置表头 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.size(); i++) { Object[] rowData = data.get(i); Row row = sheet.createRow(i + 1); for (int j = 0; j < rowData.length; j++) { Cell cell = row.createCell(j); cell.setCellValue(rowData[j].toString()); } } // 保存文件 try (FileOutputStream outputStream = new FileOutputStream(filePath)) { workbook.write(outputStream); } } } ``` 使用示例: ```java List<Object[]> data = new ArrayList<>(); data.add(new Object[] { "Tom", 18 }); data.add(new Object[] { "Jerry", 20 }); String[] headers = { "Name", "Age" }; String sheetName = "Sheet1"; String filePath = "D:/data.xlsx"; ExcelExportUtil.export(data, headers, sheetName, filePath); ``` 该工具类可以将数据列表写入 Excel 文件中,并指定表头、工作表名称和文件路径。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值