使用easyExcel的时候,没找到将excel输出为竖向的方式,特此记下excel输出为竖向的方法
注释类
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GetName {
String name() ;
}
controller层
public void downloadById(String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
String fileName = "name" + DateUtil.dateToStr(new Date(), SystemConstant.FORMATTER_M);
String userAgent = request.getHeader(ExportCode.USERAGENT);
// 解决火狐导出文件名乱码问题
try {
if (StringUtils.contains(userAgent, ExportCode.FIREFOX)) {
fileName = new String(fileName.getBytes(ExportCode.EXPORTCHARACTER), ExportCode.FILENAMECHARACTER);
} else {
fileName = URLEncoder.encode(fileName, ExportCode.EXPORTCHARACTER);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setCharacterEncoding(ExportCode.EXPORTCHARACTER);
// 设置contentType为excel格式
response.setContentType(ExportCode.CONTENTTYPE);
response.setHeader(ExportCode.CONTENT_DIS, ExportCode.HEADFILENAME + fileName + ExportCode.EXCELFORMAT);
Workbook wb = new HSSFWorkbook(); // 定义一个新的工作簿
Sheet sheet = wb.createSheet("sheet1"); // 创建第一个Sheet页
sheet.setColumnWidth(1, 31 * 256);//设置第二列的宽度是31个字符宽度
sheet.setColumnWidth(0, 31 * 256);
TStatistics statistics = statisticsService.downloadById(id);
String json = statistics.getJson();
StatisticsDto statisticsPageDto = JSONObject.parseObject(json, StatisticsDto.class);
//得到类的反射对象
Field[] list = statisticsPageDto.getClass().getDeclaredFields();
for (int i = 0; i < list.length; i++) {
Field field = list[i];
if (field.isAnnotationPresent(GetName.class)) {
field.setAccessible(true);
GetName annotation = field.getAnnotation(GetName.class);
String title = annotation.name();
String value = "";
try {
value = field.get(statisticsPageDto).toString();
} catch (Exception ignored) {
}
Row row = sheet.createRow(i); // 创建一行
//此处的要求只是一列标题,另一列为值
//标题1 value1
//标题2 value2
//标题3 value3
row.createCell(0).setCellValue(title);
row.createCell(1).setCellValue(value);
field.setAccessible(false);
}
}
ServletOutputStream fileOut = null;
try {
fileOut = response.getOutputStream();
wb.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}