- 需求:将符合查询条件的MySQL数据导出为Excel
- 导入poi依赖
<!-- poi文件工具 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency>
- 查询数据,将数据封装为一个列表(第一个参数)
- 需要为要导出的数据新建一个模板template,要和数据字段一一对应(第二个参数)
- 准备一个放Excel的文件目录(第三个参数)
- 工具类
/*
导出Excel工具类
*/
public class ExcelUtils {
/**
* @param list 表格内容结果
* @param template 模板位置
* @param basepath 文件导出路径
* @throws Exception
*/
public static String CreateExcel(List list, String template, String basepath) throws Exception {
//获得模板
FileInputStream inputStream = new FileInputStream(template);
//打开模板
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//获得名字为sheet的工作本对象,这个是看你的模板工作表的名字
XSSFSheet sheet = workbook.getSheet("sheet1");
//因为是模板,第一行有标题了,我们直接在第二行对应模板第一行插入数据即可
// 在第二行插数据
for (int i = 0; i < list.size(); i++) {
//获得第二行
XSSFRow row = sheet.createRow(i + 1);
//通过反射获得这个对象的属性字段数组
Field[] Fields = list.get(i).getClass().getDeclaredFields();
int a = 0;
for (Field field : Fields) {
//加这个才可以访问私有的属性
field.setAccessible(true);
//通过get方法得到value,等同于class.get**()
Object o = field.get(list.get(i));
//给改行的第0列赋值,后面a++,依次赋值
XSSFCell cell = row.createCell(a);
cell.setCellValue(String.valueOf(o));
a++;
}
}
//设置文件导出的保存路径
File dir = new File(basepath);
//判断当前目录是否存在
if (!dir.exists()) {
//目录不存在,需要创建
dir.mkdirs();
}
// 为导出文件命名(时间+模板名称)
template = template.substring(template.lastIndexOf("\\") + 1);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String time = dateFormat.format(new Date());
File file = new File(dir, time + template);
//创建文件
file.createNewFile();
//拿到文件的输出流
FileOutputStream fileOutputStream = FileUtils.openOutputStream(file);
//调用工作簿的write方法把这个流写出去
workbook.write(fileOutputStream);
return file.toString();
}
}