导出excel,数据为map格式

package com.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import com.netinfosz.frame.util.LogUtil;
/**
 * 杨光 导出excel工具类
 */ 
public class ExportExcelUtil {
	private List<String> headerList = new ArrayList<>();
	private List<String> keyList = new ArrayList<>();
	private SXSSFWorkbook wb;
	private SXSSFSheet sheet;
	private Map<String, CellStyle> styles;// 单元格样式

	/**
	 * 杨光
	 * 
	 * @param title
	 *            导出的excel标题 
	 * @param sheetName
	 *            sheet页名字,不传默认sheet1
	 * @param headerMap
	 *            列映射关系 key对应data中需要生成的字段代码,value 列显示的列名
	 * @param data
	 *            需要生成excel的数据
	 */
	public void exportData(String title, String sheetName, LinkedHashMap<String, String> headerMap, List<Map> data,
			OutputStream out) {
		long start=System.currentTimeMillis();
		getHeader(headerMap);
		int rownum = initWorkbook(title, sheetName);
		setDataList(rownum, headerMap, data);
		try {
			wb.write(out);
		} catch (Exception e) {
			LogUtil.error(e);
		}finally{
			try {
				wb.close();
			} catch (IOException e) {
				LogUtil.error(e);
			}
		}
		LogUtil.error("导出花费时间:"+(System.currentTimeMillis()-start)+"ms");
	}
	/**
	 * 杨光
	 * 
	 * @param title
	 *            导出的excel标题 必传
	 * @param sheetName
	 *            sheet页名字,不传默认sheet1
	 * @param headerMap
	 *            列映射关系 key对应data中需要生成的字段代码,value 列显示的列名
	 * @param data
	 *            需要生成excel的数据
	 */
	public void exportData(String title, String sheetName, LinkedHashMap<String, String> headerMap, List<Map> data,
			String filePath) {
		File file = new File(filePath);
		file.getParentFile().mkdirs();
		OutputStream out=null;
		try {
			out = new FileOutputStream(file);
			this.exportData(title, sheetName, headerMap, data, out);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			LogUtil.error("io异常",e);
		}finally{
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				LogUtil.error(e);
			}
			
		}
	}

	/**
	 * 向工作簿插入数据
	 */
	private void setDataList(int rownum, LinkedHashMap<String, String> headerMap, List<Map> dataList) {
		StringBuilder sb = new StringBuilder();
		String key;
		Object val;
		Row row;
		for (Map<Object, Object> data : dataList) {
			row = this.sheet.createRow(rownum++);
			int colunm = 0;
			for (int i = 0; i < keyList.size(); i++) {
				val = data.get(keyList.get(i));
				Cell cell = row.createCell(colunm);
				CellStyle style = styles.get("data");
				try {
					if (val == null) {
						cell.setCellValue("");
					} else if (val instanceof String) {
						cell.setCellValue((String) val);
					} else if (val instanceof Integer) {
						cell.setCellValue((Integer) val);
					} else if (val instanceof Long) {
						cell.setCellValue((Long) val);
					} else if (val instanceof Double) {
						cell.setCellValue((Double) val);
					} else if (val instanceof Float) {
						cell.setCellValue((Float) val);
					} else if (val instanceof Date) {
						DataFormat format = wb.createDataFormat();
						style.setDataFormat(format.getFormat("yyyy-MM-dd"));
						cell.setCellValue((Date) val);
					}
				} catch (Exception ex) {
					LogUtil.debug("设值 [" + row.getRowNum() + "," + colunm + "] error: " + ex.toString());
					cell.setCellValue(val.toString());
				}
				cell.setCellStyle(style);
				sb.append(val + ", ");
				colunm++;
			}
			sb.append("\n ");
		}
		LogUtil.debug("写单元格成功: \n " + sb.toString());
	}

	/**
	 * 初始化工作簿 返回占用行数
	 */
	private int initWorkbook(String title, String sheetName) {
		// 缓存500条
		this.wb = new SXSSFWorkbook(500);
		sheetName = StringUtils.isBlank(sheetName) ? "sheet1" : sheetName;
		this.sheet = wb.getSheet(sheetName);
		if (sheet == null)
			sheet = wb.createSheet(sheetName);
		styles = createStyles(wb);
		int rownum = 0;
		// 生成标题
		if (StringUtils.isNotBlank(title)) {
			Row titleRow = sheet.createRow(rownum++);
			titleRow.setHeightInPoints(30);
			Cell titleCell = titleRow.createCell(0);
			titleCell.setCellStyle(styles.get("title"));
			titleCell.setCellValue(title);
			sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
					headerList.size() - 1));
		}
		// 生成列名
		Row headerRow = sheet.createRow(rownum++);
		// 列高
		headerRow.setHeightInPoints(16);
		for (int i = 0; i < headerList.size(); i++) {
			Cell cell = headerRow.createCell(i);
			cell.setCellStyle(styles.get("header"));
			String[] ss = StringUtils.split(headerList.get(i), "**", 2);
			if (ss.length == 2) {
				cell.setCellValue(ss[0]);
				Comment comment = sheet.createDrawingPatriarch()
						.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
				comment.setString(new XSSFRichTextString(ss[1]));
				cell.setCellComment(comment);
			} else {
				cell.setCellValue(headerList.get(i));
			}
			sheet.untrackColumnForAutoSizing(i);
		}
		for (int i = 0; i < headerList.size(); i++) {
			int colWidth = sheet.getColumnWidth(i) * 2;
			sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
		}
		LogUtil.debug("--------------表格标题列名初始化ok-------------------");
		return rownum;
	}

	/**
	 * 获取列名
	 */
	private void getHeader(LinkedHashMap<String, String> headerMap) {
		for (Entry<String, String> entry : headerMap.entrySet()) {
			headerList.add(entry.getValue());
			keyList.add(entry.getKey());
		}
	}


	/**
	 * 创建表格样式
	 * 
	 * @param wb
	 *            工作薄对象
	 * @return 样式列表
	 */
	private static Map<String, CellStyle> createStyles(Workbook wb) {
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();

		CellStyle style = wb.createCellStyle();
		style.setAlignment(HorizontalAlignment.CENTER);
		style.setVerticalAlignment(VerticalAlignment.CENTER);
		Font titleFont = wb.createFont();
		titleFont.setFontName("Arial");
		titleFont.setFontHeightInPoints((short) 16);
		titleFont.setBold(true);
		style.setFont(titleFont);
		styles.put("title", style);

		style = wb.createCellStyle();
		style.setVerticalAlignment(VerticalAlignment.CENTER);
		style.setBorderRight(BorderStyle.THIN);
		style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderLeft(BorderStyle.THIN);
		style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderTop(BorderStyle.THIN);
		style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderBottom(BorderStyle.THIN);
		style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		Font dataFont = wb.createFont();
		dataFont.setFontName("Arial");
		dataFont.setFontHeightInPoints((short) 10);
		style.setFont(dataFont);
		styles.put("data", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(HorizontalAlignment.LEFT);
		styles.put("data1", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(HorizontalAlignment.CENTER);
		styles.put("data2", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(HorizontalAlignment.RIGHT);
		styles.put("data3", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		// style.setWrapText(true);
		style.setAlignment(HorizontalAlignment.CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		Font headerFont = wb.createFont();
		headerFont.setFontName("Arial");
		headerFont.setFontHeightInPoints((short) 10);
		headerFont.setBold(true);
		headerFont.setColor(IndexedColors.WHITE.getIndex());
		style.setFont(headerFont);
		styles.put("header", style);

		return styles;
	}
	public static void main(String[] args) throws FileNotFoundException {
		List<Map> data = new ArrayList<Map>();
		for (int i = 0; i < 100; i++) {
			Map<Object, Object> map = new HashMap<>();
			map.put("name", "名字" + i);
			map.put("value", "钱:" + i);
			map.put("age",  i);
			data.add(map);
		}
		LinkedHashMap<String,String> hashMap = new LinkedHashMap<>();
		hashMap.put("name", "姓名");
		hashMap.put("value", "存款");
		hashMap.put("age", "年龄");
		new ExportExcelUtil().exportData("", null, hashMap, data, "E:\\as\\abc.xls");
	}
	
	
	
	
	
	
	
	
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Java中可以使用Map对象导出Excel。可以使用第二个引用中提到的方法,将Map对象作为List的元素传递给导出Excel的方法。具体步骤如下: 1. 创建一个包含Map对象的List集合,每个Map对象代表一行数据Map的key表示Excel的列名,value表示对应的数据。 2. 调用导出Excel的方法,将List作为参数传递进去。 3. 在导出Excel的方法中,将List中的Map对象转换为Excel的行数据,并写入到Excel文件中。 例如,可以使用第二个引用中提到的方法,将Map对象导出Excel文件。假设Map对象的key为列名,value为对应的数据,可以按照以下步骤进行操作: 1. 创建一个List<Map<String, Object>>对象,将需要导出Map对象添加到List中。 2. 调用导出Excel的方法,将List作为参数传递进去。 3. 在导出Excel的方法中,将List中的Map对象转换为Excel的行数据,并写入到Excel文件中。 示例代码如下: ```java List<Map<String, Object>> dataList = new ArrayList<>(); Map<String, Object> dataMap = new HashMap<>(); dataMap.put("mc", "名称"); dataMap.put("xh", "学号"); dataMap.put("xm", "姓名"); dataMap.put("sfzh", "身份证号"); dataMap.put("xb", "性别"); dataMap.put("xl", "学历"); dataMap.put("xy", "学院"); dataMap.put("PROFESSION.zy", "专业"); dataList.add(dataMap); ExcelWriterUtil.writeToExcel(dataList, "C:\\Users\\Default\\1.xlsx"); ``` 以上代码将会将Map对象中的数据导出Excel文件,并保存在指定的路径下。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [Java实现数据导出Excel](https://blog.csdn.net/qq_28533563/article/details/78353564)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [java从List<Map>导出excel](https://blog.csdn.net/u011431937/article/details/9527725)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [java list导出excel](https://blog.csdn.net/weixin_43820898/article/details/129299733)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值