• java Excel 自用开发模板


    下载导出

    1. import com.hpay.admin.api.vo.Message;
    2. import com.hpay.admin.dubbo.IConfigDubboService;
    3. import com.hpay.admin.dubbo.IFileExportLogDubboService;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.apache.commons.lang.StringUtils;
    6. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import org.springframework.web.bind.annotation.ResponseBody;
    11. import javax.annotation.Resource;
    12. import javax.servlet.http.HttpServletResponse;
    13. import java.io.BufferedInputStream;
    14. import java.io.File;
    15. import java.io.FileInputStream;
    16. import java.io.IOException;
    17. import java.io.InputStream;
    18. import java.io.OutputStream;
    19. import java.io.UnsupportedEncodingException;
    20. import java.util.HashMap;
    21. import java.util.Map;
    22. /**
    23. * 文件公共操作
    24. * @author Garcia
    25. */
    26. @Controller
    27. @RequestMapping("/file")
    28. @Slf4j
    29. public class FileCommonController {
    30. private static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");
    31. private static final String TXT = "txt";
    32. private static final String CSV = "csv";
    33. private static final String XLS = "xls";
    34. private static final String XLSX = "xlsx";
    35. @Autowired
    36. private IConfigDubboService configService;
    37. @Resource
    38. private IFileExportLogDubboService fileExportLogDubboService;
    39. /**
    40. * 下载Excel
    41. *
    42. * @param response
    43. * @param excName
    44. */
    45. @RequestMapping("downExcel")
    46. public void downExcel(HttpServletResponse response, String excName,String fileType,String downFileName) {
    47. if (StringUtils.isBlank(excName)) {
    48. log.warn("文件名为空");
    49. return;
    50. }
    51. if (StringUtils.isBlank(fileType)) {
    52. log.warn("文件类型为空");
    53. return;
    54. }
    55. String path = configService.getProperty("tempExcelPath");
    56. String fileName = downFileName + "-" + excName;
    57. if (TXT.equals(fileType)||CSV.equals(fileType)){
    58. writeTxt(response,excName,path,fileName);
    59. }else if(XLS.equals(fileType) || XLSX.equals(fileType)){
    60. writeExcel(response,excName,path,fileName);
    61. }
    62. }
    63. private void writeTxt(HttpServletResponse response, String excName,String path,String fileName){
    64. //设置文件路径
    65. File file = new File(path + FILE_SEPARATOR + excName);
    66. if (file.exists()) {
    67. response.setContentType("application/binary; charset=UTF-8");
    68. response.setCharacterEncoding("UTF-8");
    69. try {
    70. response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName,StandardCharsets.UTF_8));
    71. } catch (UnsupportedEncodingException e) {
    72. log.error("其他错误!", e);
    73. }
    74. byte[] buffer = new byte[1024];
    75. FileInputStream fis = null;
    76. BufferedInputStream bis = null;
    77. try {
    78. fis = new FileInputStream(file);
    79. bis = new BufferedInputStream(fis);
    80. OutputStream os = response.getOutputStream();
    81. int i = bis.read(buffer);
    82. while (i != -1) {
    83. os.write(buffer, 0, i);
    84. i = bis.read(buffer);
    85. }
    86. } catch (Exception e) {
    87. log.error("写出文本文件错误!", e);
    88. } finally {
    89. if (bis != null) {
    90. try {
    91. bis.close();
    92. } catch (IOException e) {
    93. log.error("关闭流错误!", e);
    94. }
    95. }
    96. if (fis != null) {
    97. try {
    98. fis.close();
    99. } catch (IOException e) {
    100. log.error("关闭流错误!", e);
    101. }
    102. }
    103. delexcel(excName);
    104. }
    105. }
    106. }
    107. private void writeExcel(HttpServletResponse response, String excName,String path,String fileName){
    108. File file = new File(path + FILE_SEPARATOR + excName);
    109. if (file.exists()) {
    110. HSSFWorkbook wb = null;
    111. try {
    112. InputStream is = new FileInputStream(file);
    113. wb = new HSSFWorkbook(is);
    114. } catch (Exception e) {
    115. log.error("读取Excel文件错误!", e);
    116. }
    117. response.setContentType("application/binary; charset=UTF-8");
    118. response.setCharacterEncoding("UTF-8");
    119. try {
    120. response.setHeader("Content-Disposition", "attachment; filename="
    121. + URLEncoder.encode(fileName,StandardCharsets.UTF_8));
    122. } catch (UnsupportedEncodingException e) {
    123. log.error("其他错误!", e);
    124. }
    125. OutputStream os = null;
    126. try {
    127. os = response.getOutputStream();
    128. if (wb != null) {
    129. wb.write(os);
    130. }
    131. if (os != null) {
    132. os.flush();
    133. }
    134. } catch (IOException e) {
    135. log.error("写出Excel文件错误!", e);
    136. } finally {
    137. if (os != null) {
    138. try {
    139. os.close();
    140. } catch (IOException e) {
    141. log.error("关闭流错误!", e);
    142. }
    143. }
    144. delexcel(excName);
    145. }
    146. }
    147. }
    148. /**
    149. * 删除服务器Excel文件
    150. *
    151. * @param excName
    152. * @return
    153. */
    154. @RequestMapping("delExcel")
    155. @ResponseBody
    156. public Message delexcel(String excName) {
    157. String path = configService.getProperty("tempExcelPath");
    158. try{
    159. File file = new File(path + FILE_SEPARATOR + excName);
    160. long len = file.length();
    161. Thread.sleep(3000);
    162. if (len!=file.length()){
    163. return Message.error("当前文件正在操作,请稍后再删");
    164. }
    165. file.delete();
    166. fileExportLogDubboService.deleteByName(excName);
    167. }catch (Exception e){
    168. log.error("文件删除异常",e);
    169. }
    170. return Message.success();
    171. }

    生成Excel

    1. String []titles = new String[]{"",""};
    2. HSSFWorkbook wb = new HSSFWorkbook();
    3. HSSFSheet sheet=generateContentSheet(wb,titles);
    4. createRow(wb,sheet,rowList);
    5. private void createRow(HSSFWorkbook wb,HSSFSheet sheet, List> warnlist) throws ClassCastException{
    6. HSSFRow row =null;
    7. HSSFCellStyle style = wb.createCellStyle();
    8. style.setWrapText(true);
    9. for (List value : warnlist) {
    10. row = sheet.createRow(sheet.getLastRowNum() + 1);
    11. for (int i = 0; i < value.size(); i++) {
    12. Cell cell = row.createCell(i);
    13. cell.setCellStyle(style);
    14. if(value.get(i) instanceof String){
    15. cell.setCellValue((String)value.get(i));
    16. }else if(value.get(i) instanceof Integer){
    17. cell.setCellValue((Integer)value.get(i));
    18. }else if(value.get(i) instanceof Double){
    19. cell.setCellValue((Double)value.get(i));
    20. }else if(value.get(i) instanceof Boolean){
    21. cell.setCellValue((Boolean)value.get(i));
    22. }else if(value.get(i) instanceof Date){
    23. cell.setCellValue((Date)value.get(i));
    24. }else if(value.get(i) instanceof Calendar){
    25. cell.setCellValue((Calendar)value.get(i));
    26. }else if(value.get(i) instanceof RichTextString){
    27. cell.setCellValue((RichTextString)value.get(i));
    28. }else if(value.get(i) instanceof Long){
    29. cell.setCellValue((Long)value.get(i));
    30. }else if(value.get(i) instanceof BigDecimal){
    31. cell.setCellValue(value.get(i).toString());
    32. }else if(value.get(i)==null){
    33. cell.setCellValue("");
    34. }else{
    35. log.error("不支持导出类型:{},{}",value.get(i).getClass(),value.get(i));
    36. throw new ClassCastException("不支持导出类型:"+value.get(i).getClass()+","+value.get(i));
    37. }
    38. }
    39. }
    40. }
    41. private HSSFSheet generateContentSheet(HSSFWorkbook workbook,String[] titles){
    42. HSSFSheet sheet = null;
    43. sheet = workbook.createSheet("审评报告");
    44. HSSFRow row = sheet.createRow(0);
    45. sheet.autoSizeColumn(0);
    46. sheet.setColumnWidth(0,sheet.getColumnWidth(0)*17/10);
    47. sheet.autoSizeColumn(1);
    48. sheet.setColumnWidth(1,sheet.getColumnWidth(1)*27/10);
    49. sheet.autoSizeColumn(2);
    50. sheet.setColumnWidth(2,sheet.getColumnWidth(2)*17/10);
    51. sheet.autoSizeColumn(3);
    52. sheet.setColumnWidth(3,sheet.getColumnWidth(3)*17/10);
    53. sheet.autoSizeColumn(4);
    54. sheet.setColumnWidth(4,sheet.getColumnWidth(4)*17/10);
    55. CellStyle style;
    56. Font headerFont = workbook.createFont();
    57. // headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    58. style = createBorderedStyle(workbook);
    59. // style.setAlignment(CellStyle.ALIGN_CENTER);
    60. // style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
    61. // style.setFillPattern(BorderStyle.SOLID_FOREGROUND);
    62. // style.setFont(headerFont);
    63. for (int i = 0; i < titles.length; i++) {
    64. HSSFCell cell = row.createCell(i);
    65. cell.setCellValue(titles[i]);
    66. cell.setCellStyle(style);
    67. }
    68. return sheet;
    69. }
    70. /**
    71. * 生产单元格样式
    72. * @param wb
    73. * @return
    74. */
    75. private static CellStyle createBorderedStyle(Workbook wb) {
    76. CellStyle style = wb.createCellStyle();
    77. // style.setBorderRight(BorderStyle.THIN);
    78. // style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    79. // style.setBorderBottom(BorderStyle.THIN);
    80. // style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    81. // style.setBorderLeft(BorderStyle.THIN);
    82. // style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    83. // style.setBorderTop(BorderStyle.THIN);
    84. // style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    85. return style;
    86. }
    87. 相关阅读:
      关于Pytorch下载并进行部署
      Zookeeper(三)—分布式锁实现
      mysql 高性能搭建2-2: mysql5.7.29 主主复制+keepalived实现高可用
      【方向盘】认为:开发者已无理由再用Java EE
      线上问题处理案例:出乎意料的数据库连接池
      [Java] [Spring boot] Mybatis generator 生成Mapper.xml无效的问题
      C++中的auto是一个关键字,用于在编译时自动推导变量的类型
      力扣(LeetCode)775. 全局倒置与局部倒置(C++)
      【Lua 入门基础篇(九)】协程(coroutine)
      802. 找到最终的安全状态
    88. 原文地址:https://blog.csdn.net/Qensq/article/details/132947779