java xlsx 07 ,03 excel的导出

这里贴出部分关键代码 如有疑问 请联系 qq 178970412  

        我们的需求是 前端请求,把数据筛选条件传给后台,后台负责根据条件查询数据,查到之后写入到excel,然后用流的方式写入到客户端。这是基本流程 。

这是初步的导出,以后还要考虑大数据量问题

1.这是daoImpl层

	        // 导出页码 导出class的名称 导出配置j
			final ExportImport<CustomerJSONEntity> exc = new ExportImport<CustomerJSONEntity>();

			// 获取respId

			// 4.准备数据库交互参数
			ParamEntity entity = prepareDBParam(request, requestParam, DBCodeConstants.SCM_CUSTPRD_SELECT, OP_TYPE_QUERY); // 用于查询记录列表
                        
			// 查询工单表
			jsonResult = mwBDPDao.select(entity);

			if (null == JSONObject.parseObject(jsonResult, Feature.DisableSpecialKeyDetect).get("Result")) {

				throw new RuntimeException("执行transDBResult2Object异常[获取DB-Result为空]");

			}
                      /*这里可以自己封装一个集合比如Student stu = new Student(); stu.setId(1);tu.setName("小明");Student.classprivate int Id; private String name;set get 方法  快捷键 顺便说下 ctrl +alt +s 然后选择生成getter setter方法*/
                      List<CustomerJSONEntity> rowBeanList = JSONParser.transDBResult2Object(jsonResult, CustomerJSONEntity.class);
			// 生成Excel
			// 表头
			String[] headers = { "主键ID", "客户产品ID", "客户产品code", "物料ID", "基本单位ID", "客户ID", "客户物料CODE", "客户物料名称", "客户物料规格", "销售组织", "销售组", "销售人员", "计价单位", "参考价格", "生效日期", "失效日期",
                       "运输天数", "收货城市", "发货方式", "发票类型", "条形码", "生产周期", "状态" };
			OutputStream out;

			// excel 07
			// linux路径
			String fileName = fileNameforLinux(Constants.Customer, Constants.excel07);
			String filexlsx = Constants.ExcelPath + fileName;
                       // 这里换成windows路径或者 linux路径 windows一般是      String file ="D:\\java"; linux一般是tomcat的路径 这里大家测试下
			out = new FileOutputStream(new File(filexlsx));
                        //这里为了直观 直接把封装起来的名称拿来用了
			exc.createSheet(rowBeanList, "客户信息", headers, out);

			// exc.downloads(filexlsx, response);

			// excel 03
			/*
			 * String filexls = filePath(request, Constants.Material, Constants.excel03);
			 * 
			 * out = new FileOutputStream(new File(filexls));
			 * 
			 * exc.createSheet03(rowBeanList, Constants.Material, headers, out); exc.downloads(filexls, response);
			 */

2.EXPOTR关键代码

package com.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@SuppressWarnings("hiding")
public class ExportImport<T> {

	// 生成xlsx格式的调用方式 头部样式
	public static XSSFCellStyle createHeaderStyle07(XSSFWorkbook workbook) throws Exception {
		// 生成一个样式
		XSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		// 单元格颜色(颜色的索引还必须是 0x08 ~ 0x40 (8 ~ 64) 的数字)
		style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		// 单元格填充的样式
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		// 单元格边框
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setWrapText(true);// 设置自动换行
		// 单元格对齐方式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		XSSFFont font = workbook.createFont();
		// 颜色
		font.setColor(HSSFColor.VIOLET.index);
		// 字体大小
		font.setFontHeightInPoints((short) 12);
		// 粗体
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);

		return style;
	}

	// 生成xlsx格式的调用方式 内容样式
	public static XSSFCellStyle createCellStyle07(XSSFWorkbook workbook) throws Exception {
		// 生成一个样式
		XSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		// 单元格颜色(颜色的索引还必须是 0x08 ~ 0x40 (8 ~ 64) 的数字)
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		// 单元格填充的样式
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		// 单元格边框
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setWrapText(true);// 设置自动换行
		// 单元格对齐方式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		XSSFFont font = workbook.createFont();
		// 颜色
		// font.setColor(HSSFColor.VIOLET.index);
		// 字体大小
		font.setFontHeightInPoints((short) 10);
		// 粗体
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);

		return style;
	}

	// 03 头部样式
	public static HSSFCellStyle createHeaderStyle(HSSFWorkbook workbook) throws Exception {
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		// 单元格颜色(颜色的索引还必须是 0x08 ~ 0x40 (8 ~ 64) 的数字)
		style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		// 单元格填充的样式
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		// 单元格边框
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setWrapText(true);// 设置自动换行
		// 单元格对齐方式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		// 颜色
		font.setColor(HSSFColor.VIOLET.index);
		// 字体大小
		font.setFontHeightInPoints((short) 12);
		// 粗体
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);

		return style;
	}

	// 03内容样式
	public static HSSFCellStyle createCellStyle(HSSFWorkbook workbook) throws Exception {
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		// 单元格颜色(颜色的索引还必须是 0x08 ~ 0x40 (8 ~ 64) 的数字)
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		// 单元格填充的样式
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		// 单元格边框
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setWrapText(true);// 设置自动换行
		// 单元格对齐方式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		// 颜色
		// font.setColor(HSSFColor.VIOLET.index);
		// 字体大小
		font.setFontHeightInPoints((short) 10);
		// 粗体
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);

		return style;
	}

	// 03调用入口
	public void createSheet03(List<T> list, String title, String[] headers, OutputStream out) throws Exception {

		// 声明一个工作薄
		HSSFWorkbook workBook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workBook.createSheet(title);

		int index = 0;
		// 标题行
		HSSFRow row = sheet.createRow(index);
		if (headers != null) {
			for (int i = 0; i < headers.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(createHeaderStyle(workBook));
				HSSFRichTextString text = new HSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
		}

		Iterator<T> it = list.iterator();
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			createRow03(row, it.next(), workBook);

		}

		try {
			workBook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// // xls 07 创建 入口
	public void createSheet(List<T> list, String title, String[] headers, OutputStream out) throws Exception {

		// 声明一个工作薄
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 生成一个表格
		XSSFSheet sheet = workbook.createSheet(title);

		int index = 0;
		// 标题行
		XSSFRow row = sheet.createRow(index);

		if (headers != null) {
			for (int i = 0; i < headers.length; i++) {
				sheet.setColumnWidth(i, 10 * 256);
				XSSFCell cell = row.createCell(i);
				cell.setCellStyle(createHeaderStyle07(workbook));
				XSSFRichTextString text = new XSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
		}

		/*Iterator<T> it = list.iterator();
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			createRow(row, it.next(), workbook, pattern);
			
		}*/
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 1);
			createRow(row, list.get(i), workbook);
		}

		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// xlsl 07 创建行
	public void createRow(XSSFRow row, T bean, XSSFWorkbook workbook) throws Exception {
		XSSFCell cell;
		// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
		Field[] fields = bean.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {

			Field field = fields[i];
			String fieldName = field.getName();
			String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

			try {
				Class<? extends Object> tCls = bean.getClass();
				Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
				Object value = getMethod.invoke(bean, new Object[] {});

				if (value != null) {
					cell = row.createCell(i);
					cell.setCellStyle(createCellStyle07(workbook));
					if (value instanceof Integer) {
						cell.setCellValue(value.toString());

					} else {
						cell.setCellValue(value.toString());
					}
				}
			} catch (NoSuchMethodException e) {
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	// // xls 03 创建行
	public void createRow03(HSSFRow row, T bean, HSSFWorkbook workbook) throws Exception {
		HSSFCell cell;
		// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
		Field[] fields = bean.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {

			Field field = fields[i];
			String fieldName = field.getName();
			String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

			try {
				Class<? extends Object> tCls = bean.getClass();
				Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
				Object value = getMethod.invoke(bean, new Object[] {});

				if (value != null) {
					cell = row.createCell(i);
					cell.setCellStyle(createCellStyle(workbook));
					if (value instanceof Integer) {
						cell.setCellValue(value.toString());
					} else {
						cell.setCellValue(value.toString());
					}
				}
			} catch (NoSuchMethodException e) {
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public void downExcel(List<T> list, HttpServletResponse response) throws Exception {
		try {
			String path = "";
			OutputStream out = new FileOutputStream(path);
			createSheet(list, "sheet1", null, out);
			out.flush();
			out.close();
			download(path, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void downExcel(List<T> list, String title, HttpServletResponse response) throws Exception {
		try {
			String path = "";
			OutputStream out = new FileOutputStream(path);
			createSheet(list, title, null, out);
			out.flush();
			out.close();
			download(path, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void downExcel(List<T> list, String[] headers, HttpServletResponse response) throws Exception {
		try {
			String path = "";
			OutputStream out = new FileOutputStream(path);
			createSheet(list, "sheet1", headers, out);
			out.flush();
			out.close();
			download(path, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void downExcel(List<T> list, String[] headers, String title, HttpServletResponse response) throws Exception {
		try {
			String path = "";
			OutputStream out = new FileOutputStream(path);
			createSheet(list, title, headers, out);
			out.flush();
			out.close();
			download(path, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void downExcel(List<T> list, String[] headers, String title, String pattern, HttpServletResponse response, String path) throws Exception {
		try {
			OutputStream out = new FileOutputStream(path);
			createSheet(list, title, headers, out);
			out.flush();
			out.close();
			System.out.println(path);
			download(path, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void download(String path, HttpServletResponse response) throws Exception {
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void downloads(String path, HttpServletResponse response) throws IOException {
		// path是指欲下载的文件的路径。
		File file = new File(path);
		// 取得文件名。
		String filename = file.getName();
		// 取得文件的后缀名。
		// String ext = filename.substring(filename.lastIndexOf(".") +
		// 1).toUpperCase();

		// 以流的形式下载文件。
		InputStream fis = new BufferedInputStream(new FileInputStream(path));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();
		// 清空response
		response.reset();
		// 设置response的Header
		response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/octet-stream;charset=utf-8");
		 response.setCharacterEncoding("UTF-8");//设置Response的编码方式为UTF-8
	/*	PrintWriter writer = response.getWriter();

		writer.write("中国");*/
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
	}

	public static void downloadFile(URL theURL, String filePath) throws IOException {
		File dirFile = new File(filePath);
		if (!dirFile.exists()) {// 文件路径不存在时,自动创建目录
			dirFile.mkdir();
		}
		// 从服务器上获取图片并保存
		URLConnection connection = theURL.openConnection();
		InputStream in = connection.getInputStream();
		FileOutputStream os = new FileOutputStream(filePath + "\\666.xlsx");
		byte[] buffer = new byte[4 * 1024];
		int read;
		while ((read = in.read(buffer)) > 0) {
			os.write(buffer, 0, read);
		}
		os.close();
		in.close();
	}
}

3. 前端ajax请求解决方案 

    前端ajax请求无法接受流,能接受html text 等, 所以可以先生成文件到服务器,返回给前端文件名称,然后用window.location.href="url"; 封装个方法单独下载(我的类里面已经封装好了,可以拿来用,如果大家有好的方式方法 一起交流   会非常感谢各位大牛的指导)



追加: pom.xml文件  扎包依赖


<!-- poi核心包 -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.9</version>
		</dependency>
		<!-- 导入时使用的依赖包 -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.9</version>
		</dependency>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值