package com.rd.lh.util.excel;

import java.beans.PropertyDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtilsBean;
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.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.rd.ifaes.common.util.BigDecimalUtils;
import com.rd.ifaes.common.util.DateUtils;
import com.rd.ifaes.common.util.StringUtils; /**
* excel 导出工具类
* @author lh
* @version 3.0
* @since 2016-11-8
*
*/
public class ExportUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ExportUtil.class); private static final int sheetMaxCount = 1000000;//单个sheet最多写入行数 public static <T> void exportExcel(String title, String[] headers, String[] fields, int startRow, Workbook wb, List<T> data) throws IOException { Sheet sheet = null;
startRow = startRow>0?startRow+2:startRow;
int index = startRow, pageRowNo = startRow, columnCount = headers.length; // 行号、页码、列数 for (T obj : data) {
int sheetIndex = index/sheetMaxCount;
if (index % sheetMaxCount == 0) {
sheet = wb.createSheet(title + "_" + (sheetIndex + 1));
sheet = wb.getSheetAt(sheetIndex);
sheet.setDisplayGridlines(false);// 设置表标题是否有表格边框
pageRowNo = 2;
createHeader(sheet, title, headers);
}else{
sheet = wb.getSheetAt(sheetIndex);
}
index++;
@SuppressWarnings("unchecked")
Map<String, Object> map = obj instanceof Map ? (Map<String, Object>) obj : beanToMap(obj);
Row nRow = sheet.createRow(pageRowNo++); // 新建行对象
for (int j = 0; j < columnCount; j++) {
Cell cell = nRow.createCell(j);
setCellValue(sheet, cell, map.get(fields[j]));
}
} } /**
* write Workbook
* @param wb
* @param filePath
* @throws IOException
*/
public static void writeWorkbook(Workbook wb, String filePath)throws IOException{
FileOutputStream fos = new FileOutputStream(filePath + "/workbook.xlsx");
wb.write(fos);
fos.flush();
fos.close();
wb.close();
} /**
* responseWorkbook
* @param title
* @param wb
* @param request
* @param response
* @throws IOException
*/
public static void responseWorkbook(String title, Workbook wb,HttpServletRequest request, HttpServletResponse response)throws IOException{
String sFileName = title + ".xlsx";
// 火狐浏览器导出excel乱码
String agent = request.getHeader("User-Agent");
// 判断是否火狐浏览器
boolean isFirefox = agent != null && agent.contains("Firefox");
if (isFirefox) {
sFileName = new String(sFileName.getBytes("UTF-8"), "ISO-8859-1");
} else {
sFileName = URLEncoder.encode(sFileName, "UTF8");
}
response.setHeader("Content-Disposition", "attachment; filename=".concat(sFileName));
response.setHeader("Connection", "close");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
wb.write(response.getOutputStream());
}
/**
* 设置单元格的值
* @param cell
* @param cellVal
*/
public static void setCellValue(Sheet sheet, Cell cell, Object cellVal){
if(cellVal == null || String.class.equals(cellVal.getClass())){
cell.setCellValue(StringUtils.isNull(cellVal));
}else if(Integer.class.equals(cellVal.getClass()) || int.class.equals(cellVal.getClass())){
cell.setCellValue(Integer.valueOf(cellVal.toString()));
}else if(Long.class.equals(cellVal.getClass()) || long.class.equals(cellVal.getClass())){
cell.setCellValue(Integer.valueOf(cellVal.toString()));
}else if(Double.class.equals(cellVal.getClass()) || double.class.equals(cellVal.getClass())){
cell.setCellValue(Double.valueOf(cellVal.toString()));
}else if(Float.class.equals(cellVal.getClass()) || float.class.equals(cellVal.getClass())){
cell.setCellValue(Float.valueOf(cellVal.toString()));
}else if(BigDecimal.class.equals(cellVal.getClass())){
cell.setCellValue(BigDecimalUtils.round(cellVal.toString()).doubleValue());
}else if(Date.class.equals(cellVal.getClass())){
cell.setCellValue(DateUtils.formatDateTime((Date)cellVal));
}else if(Timestamp.class.equals(cellVal.getClass())){
cell.setCellValue(DateUtils.formatDateTime((Timestamp)cellVal));
}else{
cell.setCellValue(StringUtils.isNull(cellVal));
}
cell.setCellStyle(sheet.getWorkbook().getCellStyleAt(3));
} /**
* JavaBean转Map
*
* @param obj
* @return
*/
public static Map<String, Object> beanToMap(Object obj) {
Map<String, Object> params = new HashMap<>(0);
try {
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
if (!StringUtils.equals(name, "class")) {
params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
}
}
} catch (Exception e) {
LOGGER.error("URLDecoder fail :", e);
}
return params;
} /**
* 创建表头
* @param sheet
* @param headers
*/
private static void createHeader(Sheet sheet, String title, String[] headers){ //设置标题
Row tRow = sheet.createRow(0);
Cell hc = tRow.createCell(0);
hc.setCellValue(new XSSFRichTextString(title));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));// 合并标题行:起始行号,终止行号, 起始列号,终止列号
hc.setCellStyle(sheet.getWorkbook().getCellStyleAt(1)); //设置表头
Row nRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = nRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(sheet.getWorkbook().getCellStyleAt(2));
}
} /**
* 创建Workbook
* @return
*/
public static Workbook createWorkbook(){
Workbook wb = new SXSSFWorkbook(100);
CellStyle hcs = wb.createCellStyle();
hcs.setBorderBottom(BorderStyle.THIN);
hcs.setBorderLeft(BorderStyle.THIN);
hcs.setBorderRight(BorderStyle.THIN);
hcs.setBorderTop(BorderStyle.THIN);
hcs.setAlignment(HorizontalAlignment.CENTER);
Font hfont = wb.createFont();
hfont.setFontName("宋体");
hfont.setFontHeightInPoints((short) 16);// 设置字体大小
hfont.setBold(true);// 加粗
hcs.setFont(hfont); CellStyle tcs = wb.createCellStyle();
tcs.setBorderBottom(BorderStyle.THIN);
tcs.setBorderLeft(BorderStyle.THIN);
tcs.setBorderRight(BorderStyle.THIN);
tcs.setBorderTop(BorderStyle.THIN);
Font tfont = wb.createFont();
tfont.setFontName("宋体");
tfont.setFontHeightInPoints((short) 12);// 设置字体大小
tfont.setBold(true);// 加粗
tcs.setFont(tfont); CellStyle cs = wb.createCellStyle();
cs.setBorderBottom(BorderStyle.THIN);
cs.setBorderLeft(BorderStyle.THIN);
cs.setBorderRight(BorderStyle.THIN);
cs.setBorderTop(BorderStyle.THIN);
Font font = wb.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 12);// 设置字体大小 return wb;
} } 转自:http://hbxflihua.iteye.com/blog/2336173

转:POI操作Excel导出的更多相关文章

  1. java使用POI操作excel文件,实现批量导出,和导入

    一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...

  2. POI操作Excel

    POI和Excel简介 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作 ...

  3. POI操作Excel(xls、xlsx)

    阿帕奇官网:http://poi.apache.org/ POI3.17下载:http://poi.apache.org/download.html#POI-3.17 POI操作Excel教程(易百教 ...

  4. 自己封装的poi操作Excel工具类

    自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...

  5. 自己的包poi操作Excel工具

    在前面的文章<使用poi读写Excel>中分享了一下poi操作Excel的简单演示样例.这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完毕的功能是:读取Excel.汇总E ...

  6. Java POI操作Excel注意点

    excel的行索引和列索引都是从0开始,而行号和列号都是从1开始 POI·操作excel基本上都是使用索引 XSSFRow对象的 row.getLastCellNum() 方法返回的是当前行最后有效列 ...

  7. 使用POI操作Excel时对事先写入模板的公式强制执行

    场景:POI读取Excel模板. 当使用POI操作Excel时,发现由POI生成的公式能够在打开Excel是被执行, 而事先手工写入Excel模板文件的公式则不自动被调用,必须手动双击该Cell才能生 ...

  8. POI操作Excel异常Cannot get a text value from a numeric cell

    控制台抛出异常:java.lang.IllegalStateException: Cannot get a text value from a numeric cell 在java中用POI解析exc ...

  9. 利用Apache POI操作Excel

    最近在做接口,有个功能是利用Excel导入汽车发动机所需零件信息到线上系统中.简单回顾一下之前学过的用java操作Excel. 1.maven配置Apache POI pom.xml中配置POIjar ...

随机推荐

  1. 多条件分页查找(SQL拼接方法)

    def startTime=params.startTime+" 00:00:00"  def endTime=params.endTime + " 23:59:59&q ...

  2. java第三周学习

    这一周学习的是java数组面向对象 数组中存放的数据的类型:既可以是基本数据类型也可以是引用数据类型. 数组的定义方式: 1 数据类型[] 数组名; 2 数据类型 数组名[]; 数组的初始化: 1.静 ...

  3. 【poj3270】 Cow Sorting

    http://poj.org/problem?id=3270 (题目链接) 题意 n个数要要按从小到大的顺序排列,每次只能交换任意两个数,交换的代价为这两个数之和,问最小代价. Solution 题目 ...

  4. Java加载资源文件几种方法

    from: http://andyzhu.blog.51cto.com/4386758/775836/ import java.net.URL; import org.springframework. ...

  5. java在线支付

    http://blog.csdn.net/lidew521/article/category/1437251

  6. 20145212——GDB调试汇编堆栈过程分析

    GDB调试汇编堆栈过程分析 测试代码 #include <stdio.h> short val = 1; int vv = 2; int g(int xxx) { return xxx + ...

  7. web中c#纯网站中引用log4net模块,不记录日志

    如题,解决如下: 1.log4net.config配置如下: <?xml version="1.0" encoding="utf-8" ?> < ...

  8. vtkPlane和vtkPlaneSource

    1.vtkPlane vtkPlane provides methods for various plane computations. These include projecting points ...

  9. html5 Websockets development guidance

    1. WebSockets -- full-duplex communication The main HTML5 pillars include Markup, CSS3, and JavaScri ...

  10. Workflow 中做拒绝操作时强制输入拒绝信息

    在做AP发票审批驳回时,客户要求必须强制输入拒绝原因,代码如下: PROCEDURE Validate_Response ( Itemtype IN VARCHAR2, Itemkey IN VARC ...