Java操作poi导出Excel报表

本文介绍了一个使用Java实现的Excel导出工具类,通过该工具类可以方便地将Java对象集合导出到Excel文件中。文章提供了详细的代码示例,包括如何设置表格标题、动态获取JavaBean属性值及导出文件的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


依赖:

<dependency>

<groupId>org.apache.poi</groupId>

  <artifactId>poi-ooxml</artifactId> 

<version>3.9</version> 

</dependency>



import java.io.BufferedOutputStream;  

import java.lang.reflect.Field; 

import java.lang.reflect.Method;

import java.util.Collection;  

import java.util.Iterator;   

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;

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;   

  /*

 * excel导出文件

* @author GuiqiHu

 * @date

*/ 

public class ExportExcel<T> {  

public void exportExcel(String[] headers,Collection<T> dataset, String fileName,HttpServletResponse response) {  

  // 声明一个工作薄   

 XSSFWorkbook workbook = new XSSFWorkbook();  

// 生成一个表格 

XSSFSheet sheet = workbook.createSheet(fileName);

 // 设置表格默认列宽度为15个字节

 sheet.setDefaultColumnWidth((short20);       

 // 产生表格标题行

XSSFRow row = sheet.createRow(0); 

for (short i = 0; i < headers.length; i++) { 

XSSFCell cell = row.createCell(i); 

XSSFRichTextString text = new XSSFRichTextString(headers[i]); 

cell.setCellValue(text);    

   }  

 try {  

// 遍历集合数据,产生数据行 

Iterator<T> it = dataset.iterator(); 

int index = 0;  

while (it.hasNext()) {     

 index++;  

row = sheet.createRow(index);  

T t = (T) it.next();    

// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值 Field[] fields = t.getClass().getDeclaredFields();  

for (short i = 0; i < headers.length; i++) { 

XSSFCell cell = row.createCell(i);

Field field = fields[i];

String fieldName = field.getName();         

String getMethodName = "get" + fieldName.substring(01).toUpperCase() + fieldName.substring(1);     

Method getMethod = t.getClass().getMethod(getMethodName, new Class[] {});      

Object value = getMethod.invoke(t, new Object[] {});   

// 判断值的类型后进行强制类型转换 

String textValue = null;  

// 其它数据类型都当作字符串简单处理 

if(value != null && value != ""){   

textValue = value.toString();  

if (textValue != null) {

XSSFRichTextString richString = new XSSFRichTextString(textValue);  

 cell.setCellValue(richString);

    }   

   } 

getExportedFile(workbook, fileName,response);    

catch (Exception e) {  

  e.printStackTrace(); 

   }    

  }      

  /** 

 *

*方法说明: 指定路径下生成EXCEL文件

*@return

*/      public void getExportedFile(XSSFWorkbook workbook, String name,HttpServletResponse response) throws Exception { 

BufferedOutputStream fos = null;

try {  

String fileName = name + ".xlsx"

response.setContentType("application/x-msdownload");

//response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");       

response.setHeader("ContentDisposition""attachment;filename=" + new String(fileName.getBytes("gb2312"),"ISO8859-1"));

fos = new BufferedOutputStream(response.getOutputStream()); 

 workbook.write(fos);

  } catch (Exception e) {

  e.printStackTrace();  

  } finally {  

   if (fos != null) {

 fos.close();   } 

   }

  }   

 } 


controller层代码

//导出Eccel 
@RequestMapping
("exportUser")
public void exportUser(Model model,HttpServletResponse response){   List<User> userList = userService.selectUserList();
  ExportExcel<User> ee= new ExportExcel<User>(); 
  String[] headers = { "序号""姓名""性别""年龄" };
   String fileName = "用户信息表"long start = System.currentTimeMillis();  

  1. ee.exportExcel(headers,userList,fileName,response);

  2.  long end = System.currentTimeMillis(); 

  3. System.out.println("导出数据共用了:"+(end-start)+"毫秒"); 

  4.  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值