自己整理的POI导出Excel:
-
pox.xml 配置文件里面添加 poi:
这里使用的是POI3.16版本——POI
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.16</version>
</dependency>
<!-- POI end -->
ExportExcel工具:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
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.ss.usermodel.HorizontalAlignment;
public class ExportExcel<T> {
/**
* 这一段为测试代码;
* 测试实体类:(直接封装即可)
* public class Student {
* private Integer id;
* private String name;
* private String sex;
*/
public static void main(String[] args) {
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 声明一个单子并命名
HSSFSheet sheet = wb.createSheet("学生表");
// 给单子名称一个长度
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
HSSFCellStyle style = wb.createCellStyle();
// 创建第一行(也可以称为表头)
HSSFRow row = sheet.createRow(0);
// 样式字体居中
style.setAlignment(HorizontalAlignment.CENTER);
// 给表头第一行一次创建单元格
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("学生编号");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("学生姓名");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("学生性别");
cell.setCellStyle(style);
// 添加一些数据,这里先写死,大家可以换成自己的集合数据
List<Student> list = new ArrayList<Student>();
list.add(new Student(123, "123", "465"));
list.add(new Student(111, "李四", "男"));
list.add(new Student(111, "王五", "女"));
// 向单元格里填充数据
for (short i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(list.get(i).getId());
row.createCell(1).setCellValue(list.get(i).getName());
row.createCell(2).setCellValue(list.get(i).getSex());
}
try {
// 默认导出到E盘下
FileOutputStream out = new FileOutputStream("E://学生表.xls");
wb.write(out);
out.close();
JOptionPane.showMessageDialog(null, "导出成功!");
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "导出失败!");
e.printStackTrace();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "导出失败!");
e.printStackTrace();
}
}
//测试结束;
//************************
/**
*
* @param title
* 表格标题名
* @param headersName
* 表格属性列名数组
* @param headersId
* 表格属性列名对应的字段
* @param dataset
* 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
*/
public void exportExcel(String title, String[] headersName,
String[] headersId, List<T> dtoList) {
// 表头
Map<Integer, String> map = new HashMap<Integer, String>();
int key = 0;
for (int i = 0; i < headersName.length; i++) {
if (!headersName[i].equals(null)) {
map.put(key, headersName[i]);
key++;
}
}
// 字段
Map<Integer, String> zdMap = new HashMap<Integer, String>();
int value = 0;
for (int i = 0; i < headersId.length; i++) {
if (!headersId[i].equals(null)) {
zdMap.put(value, headersId[i]);
value++;
}
}
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(title);
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
HSSFCellStyle style = wb.createCellStyle();
HSSFRow row = sheet.createRow(0);
style.setAlignment(HorizontalAlignment.CENTER);
HSSFCell cell;
Collection c = map.values();
Iterator<String> it = c.iterator();
// 根据选择的字段生成表头
short size = 0;
while (it.hasNext()) {
cell = row.createCell(size);
cell.setCellValue(it.next().toString());
cell.setCellStyle(style);
size++;
}
// 字段
Collection zdC = zdMap.values();
Iterator<T> labIt = dtoList.iterator();
int zdRow = 0;
while (labIt.hasNext()) {
// int zdCell = 0;
zdRow++;
row = sheet.createRow(zdRow);
T l = (T) labIt.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = l.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
// String fieldName = field.getName();
Object val;
try {
val = field.get(l);
// System.out.println(val);
String type = field.getType().toString();// 得到此属性的类型
// System.out.println(type);
if (type.endsWith("String")) {
row.createCell(i).setCellValue((String) val);
} else if (type.endsWith("int") || type.endsWith("Integer")) {
row.createCell(i).setCellValue((double) val);
} else if (type.endsWith("Boolean")) {
row.createCell(i).setCellValue((boolean) val);
} else if (type.endsWith("Date")) {
// 如果是日期格式,设置单元格格式;
HSSFCell cella = row.createCell(i);
cella.setCellValue((Date) val);
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFDataFormat format = wb.createDataFormat();
cellStyle.setDataFormat(format.getFormat("yyyy-MM-dd"));
cella.setCellStyle(cellStyle);
} else if (type.endsWith("Timestamp")) {
// 如果是日期格式,设置单元格格式;
HSSFCell cella = row.createCell(i);
cella.setCellValue((Date) val);
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFDataFormat format = wb.createDataFormat();
cellStyle.setDataFormat(format
.getFormat("yyyy-MM-dd HH:mm"));
cella.setCellStyle(cellStyle);
} else if (type.endsWith("BigDecimal")) {
row.createCell(i).setCellValue((double) val);
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
FileOutputStream xls = new FileOutputStream("E://学生表AB.xls");
wb.write(xls);
xls.close();
// JOptionPane.showMessageDialog(null, "导出成功!");
} catch (FileNotFoundException e) {
// JOptionPane.showMessageDialog(null, "导出失败!");
e.printStackTrace();
} catch (IOException e) {
// JOptionPane.showMessageDialog(null, "导出失败!");
e.printStackTrace();
}
}
}
控制器Controller:
/**
*
* @return
*/
@RequestMapping("/outexcel")
public String outall() {
String title = "表名称";
//列名称:
String[] headersName = { "一", "二", "三", "四", "五", "六", "七", "八", "九",
"十", "十一", "十二" };
//对应实体名(顺序一致);
String[] headersId = { "StoreLevelId", "SingleStoresLevel", "isShow",
"SlState", "StoreLevelItemId", "LevelItemName", "FieldType",
"OrderValue", "BusinessExplain", "SliState" };
//数据集合
List<StoreLevelResult> dtoList = sLevelServices.getLevelResults();
excel.exportExcel(title, headersName, headersId, dtoList);
//重定向
return "redirect:***";
}
测试效果
*
*
*
笔记;
我是一个新手;正在慢慢充实自己;
文章内容转载自:
Java利用POI实现数据的Excel导出