ServletRequestAttributes servletRequestAttributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
HttpServletRequest request = servletRequestAttributes.getRequest();
String fileName = request.getParameter("fileName");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
ServletOutputStream outputStream = null;
List<Client> clients = new ArrayList<Client>();
clients.add(new Client("1", "100", "01"));
clients.add(new Client("2", "200", "02"));
List<String> biaoti = new ArrayList<String>(Arrays.asList("客户", "金额", "币种"));
List<Integer> width = new ArrayList<>(
Arrays.asList(4000, 6000, 8000)
);
// 创建工作簿
HSSFWorkbook wb = new HSSFWorkbook();
// 创建工作表
HSSFSheet sheet = wb.createSheet("客户");
// 创建一行,行的索引从0开始,第一行为标题
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
// 设置第一行标题
for (int i = 0; i < biaoti.size(); i++) {
// 创建单元格,列的索引从0开始
cell = row.createCell(i);
cell.setCellValue(biaoti.get(i));
sheet.setColumnWidth(i,width.get(i));
}
int rowcount = 1; //注意,excel第一行为标题,因此rowcount从1开始第二行填充数据
try {
for (int i = 0; i < clients.size(); i++) {
// 等于row = sheet.createRow(rowcount) ; rowcount++
row = sheet.createRow(rowcount++);
// 如果展示字段过多,考虑使用反射
Client client = clients.get(i); //Client对应excel展示字段,顺序保持一致
Field[] fields = client.getClass().getDeclaredFields(); //获取对应的所有展示字段
Map<String, String> map = new HashMap<>();
for (int j = 0; j < fields.length; j++) { //fields中属性顺序和Client属性顺序一致
Field field = fields[j];
field.setAccessible(true);
String name = field.getName(); // 属性名称
String value = String.valueOf(field.get(client)); //当前对象该属性的值
row.createCell(j).setCellValue(value); //设置
}
}
outputStream = response.getOutputStream();
wb.write(outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
poi实现excel导出
最新推荐文章于 2023-08-06 18:35:56 发布