前端大概的样式:

模板:

效果:

HTML:

<span class="l" style="margin-left: 10px;"><a class="btn btn-primary radius" data-title="导出明细记录" onclick="downloadExcelDetails()" href="#"><i class="Hui-iconfont"></i> 导出明细记录</a>
</span>

JS:

//导出Excel公共方法function downloadExcelDetails() {var logmin = $("#logmin").val();var logmax = $("#logmax").val();var compname = $("#compname").val();var area_name = $("#p_status").val();var d_type = $("#d_type").val();//条件判断省略//.....window.location.href = "<%=basePath%>inspection/publicDownloadExcel.cyl?sDate="+ logmin +"&eDate="+ logmax +"&villageName="+ compname +"&area_name="+ area_name +"&d_type="+ d_type;}

控制层( 根据个人需求修改,代码写的有点乱,没有什么设计模式,新手上路请多指教!):

@ResponseBody@RequestMapping(value = "publicDownloadExcel")public void downloadExcelQueryData(HttpServletRequest request, HttpServletResponse response, String sDate, String eDate, String villageName, String d_type, String area_name, Authentication authentication) throws IOException {SessionUser sessionUser = (SessionUser) authentication.getPrincipal();String excelPathP = null;String excelNameP = null;Map<String, String> resultList = new HashMap<String, String>();//导出明细if (area_name != null && !area_name.equals("")) {//导出明细String templatefile = request.getServletContext().getRealPath("/");if (d_type != null && d_type.equals("0")) {templatefile += "excleTemplate/AreaTemplate.xlsx";//小区}if (d_type != null && d_type.equals("1")){templatefile += "excleTemplate/CompanyTemplate.xlsx";//单位}List<ljCheckBodyTarget> resultDetailsList = dailyInService.queryDetailsInfoBydateAndvillageName(sDate, eDate, villageName, d_type, area_name, sessionUser.getLevel(), sessionUser.getId());resultList = ExportExcelUtil.putInto1Excel(request.getServletContext(), null, resultDetailsList, templatefile, d_type);excelPathP = resultList.get("path");excelNameP = resultList.get("name");}//文件流的方式导出Exceltry {// 输出响应正文的输出流OutputStream out;// 读取本地文件的输入流InputStream in;// 获得本地输入流File file = new File("C:\\"+ excelPathP + excelNameP);in = new FileInputStream(file);// 设置响应正文的MIME类型response.setContentType("application/octet-stream;charset=UTF-8");String fileName = new String(excelNameP.getBytes("gb2312"), "iso8859-1");response.setHeader("Content-disposition", "attachment;filename=" + fileName);// 把本地文件发送给客户端out = response.getOutputStream();int byteRead = 0;byte[] buffer = new byte[512];while ((byteRead = in.read(buffer)) != -1) {out.write(buffer, 0, byteRead);}in.close();out.flush();out.close();} catch (Exception e) {e.printStackTrace();logger.error("文件下载出现异常", e); } }

生成Excel:

package com.cyl.util;import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.imageio.ImageIO;
import javax.servlet.ServletContext;import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import com.cyl.model.ljCheckBodyTarget;
import com.cyl.model.ljCheckInstanceM;public class ExportExcelUtil {private static Logger log = Logger.getLogger(ExportExcelUtil.class);/*** 利用List<LinkedHashMap>导出Excel,保证顺序,纯导出数据* * @param context*            上下文会话对象* @param dicument*            生成文件的目錄文件名,參數為空時默認為excel* @param list*            Unallowable类数据集* @param templatefile *                  模板路径* @param d_type 0区域 1单位* * @return path返回路徑;name文件名;*/public static Map<String, String> putInto1Excel(ServletContext context, String dicument,List<ljCheckBodyTarget> list, String templatefile, String d_type){Map<String, String> result = new HashMap<String, String>();InputStream ins = null;XSSFWorkbook wb = null;XSSFSheet sheet = null;XSSFRow row = null;FileOutputStream out = null;Cell cell = null;if(!new File(templatefile).exists()){System.out.println("文件不存在,已创建");wb = new XSSFWorkbook();sheet = wb.createSheet();} else {System.out.println("文件存在,读取流");try {ins = new FileInputStream(templatefile);wb = new XSSFWorkbook(ins);sheet = wb.getSheetAt(0);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}int currentLastRowIndex = sheet.getLastRowNum();row = sheet.createRow(currentLastRowIndex + 1);try {String fileName = TUtil.format("yyyy_MM_dd_HHmmssSSSSSS");String filePath = null;for (int i = 0; i < list.size(); i++) {ljCheckBodyTarget data = list.get(i);if (i == 0) {//文件名称拼接我所要命名的文件名fileName += "-"+ data.getAreaName();fileName += ".xlsx";row = sheet.getRow(2);//获取第二行SimpleDateFormat sdf = new SimpleDateFormat("yyyy");SimpleDateFormat mm = new SimpleDateFormat("MM");cell = row.getCell(0);//第0列cell.setCellValue(sdf.format(data.getCheckDate()) +"年"+ mm.format(data.getCheckDate()) +"月"+ data.getAreaName());cell.setCellStyle(cellSetStyle(wb, 0, 1));//Excel样式生成调用}row = sheet.createRow(currentLastRowIndex + i + 1);if (d_type != null) {cell = row.createCell(0);cell.setCellValue( i + 1);cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(1); cell.setCellValue(data.getAreaName());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(2);cell.setCellValue(data.getVillageType());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(3);cell.setCellValue(data.getVillageName());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(4);cell.setCellValue(data.getTotalScore());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(5);if (Double.parseDouble(data.getTotalScore()) >= 90) {cell.setCellStyle(cellSetStyle(wb, 0, 0));cell.setCellValue("达标");}else if (Double.parseDouble(data.getTotalScore()) >= 80){cell.setCellStyle(cellSetStyle(wb, 0, 0));cell.setCellValue("未达标");}else {cell.setCellStyle(cellSetStyle(wb, 1, 0));cell.setCellValue("未达标");}cell = row.createCell(6);cell.setCellValue(data.getAttr1());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(7);cell.setCellValue(data.getAttr2());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(8);cell.setCellValue(data.getAttr3());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(9);cell.setCellValue(data.getAttr4());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(10);cell.setCellValue(data.getAttr5());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(11);cell.setCellValue(data.getAttr6());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(12);cell.setCellValue(data.getAttr7());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(13);cell.setCellValue(data.getAttr8());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(14);cell.setCellValue(data.getAttr9());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(15);cell.setCellValue(data.getAttr10());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(16);cell.setCellValue(data.getAttr11());cell.setCellStyle(cellSetStyle(wb, 0, 0));if (!d_type.equals("1")) {//1代表单位cell = row.createCell(17);cell.setCellValue(data.getAttr12());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(18);cell.setCellValue(data.getAttr13());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(19);cell.setCellValue(data.getAttr14());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(20);cell.setCellValue(data.getAttr15());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(21);cell.setCellValue(data.getAttr16());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(22);cell.setCellValue(data.getAttr17());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(23);cell.setCellValue(data.getAttr18());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(24);cell.setCellValue(data.getAttr19());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(25);cell.setCellValue(data.getAttr20());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(26);cell.setCellValue(data.getAttr21());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(27);cell.setCellValue(data.getAttr22());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(28);cell.setCellValue(data.getAttr23());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(29);cell.setCellValue(data.getAttr24());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(30);cell.setCellValue(data.getAttr25());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(31);cell.setCellValue(data.getAttr26());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(32);cell.setCellValue(data.getAttr27());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(33);cell.setCellValue(data.getAttr28());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(34);cell.setCellValue(data.getAttr29());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(35);cell.setCellValue(data.getAttr30());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(36);cell.setCellValue(data.getAttr31());cell.setCellStyle(cellSetStyle(wb, 0, 0));cell = row.createCell(37);cell.setCellValue(data.getAttr32());cell.setCellStyle(cellSetStyle(wb, 0, 0));}}}//String mes = context.getRealPath("/");String relpath = (StringUtils.isBlank(dicument) ? "excel" : dicument) + "/";filePath = "C:\\" + relpath;// 文件存放路径File fileDir = new File(filePath);if (!(fileDir.exists() && fileDir.isDirectory())) {new File(filePath).mkdirs();}result.put("path", relpath);result.put("name", fileName);out = new FileOutputStream(filePath + fileName);wb.write(out);} catch (FileNotFoundException e) {e.printStackTrace();log.error(e.getMessage());} catch (IOException e) {e.printStackTrace();log.error(e.getMessage());}finally {try {out.close();} catch (IOException e) {e.printStackTrace();}}return result;}/*** 显示单元格,设置字体颜色* @param wb* @param mark* @return*/public static CellStyle cellSetStyle(XSSFWorkbook wb, int mark, int boldMark) {//创建样式1XSSFCellStyle style = wb.createCellStyle();//设置边框样式style.setBorderBottom(CellStyle.BORDER_THIN);style.setBorderLeft(CellStyle.BORDER_THIN);style.setBorderRight(CellStyle.BORDER_THIN);style.setBorderTop(CellStyle.BORDER_THIN);// 指定单元格居中对齐     style.setAlignment(XSSFCellStyle.ALIGN_CENTER);     // 指定单元格垂直居中对齐     style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);if (mark != 0 || boldMark != 0) {//设置字体XSSFFont font = wb.createFont();if (mark == 1) {//颜色标记 1 红色font.setColor((short)60);//设置字体颜色}if (boldMark == 1) {//标记 1为加粗//自动换行style.setWrapText(true);//设置字体样式font.setFontName("宋体");//设置字体大小font.setFontHeightInPoints((short) 9);//设置字体font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);//粗体显示}style.setFont(font);//选择需要用到的字体格式}return style;}}

基础类(根据个人需求取需要的):

package com.cyl.util;import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;import org.apache.log4j.Logger;/*** 基础类* * @author Qiang1_Zhang*/
public class TUtil {static Logger log = Logger.getLogger(TUtil.class);/*** 日期转换函数* * @param format*            需要转换的格式* @return 转换后的日期*/public static String format(String format) {return new SimpleDateFormat(format).format(new Date());}/*** 日期转换函数* * @param format*            需要转换的格式* @return 转换后的日期*/public static String format(Date date, String format) {return new SimpleDateFormat(format).format(date);}/*** 打印函数* * @param str*            对象类型*/public static void print(Object str) {System.out.println(str);}/*** 计算距今指定天数的日期* * @param day*            相差的天数,可为负数* @return 计算之后的日期*/public static String GetDay(int day) {Calendar cal = Calendar.getInstance();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");cal.setTime(new Date());// 设置日历时间cal.add(Calendar.DAY_OF_MONTH, day);// 天数String strDate = sdf.format(cal.getTime());// 得到你想要的天数return strDate;}/*** 获取报表模板路径* * @return*/public static String getURL() {String dir = System.getProperty("user.dir");print("dir=" + dir);dir = dir.substring(0, dir.lastIndexOf("\\"));String filePath = dir;return filePath;}/*** String类型日期转换为长整型* * @param date*            String类型日期* @param format*            日期格式* @return long*/public static long strDateToLong(String date, String... format) {String format1 = null;if (format.length != 0) {format1 = format[0];} else {format1 = "yyyy-MM-dd HH:mm:ss";}String sDt = date;SimpleDateFormat sdf = new SimpleDateFormat(format1);long lTime = 0;try {Date dt2 = sdf.parse(sDt);lTime = dt2.getTime();print(lTime);} catch (ParseException e) {e.printStackTrace();}return lTime;}public static void longToString(long l) {format("");}/*** 获取文件创建时间* * @param file*            文件目录*/public static String getCreateTime(File file) {// file = new File("e:/1.xls");String date = "";// file.lastModified();try {Process process = Runtime.getRuntime().exec("cmd.exe /c dir " + file.getAbsolutePath() + "/tc");InputStream is = process.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));for (int i = 0; i < 5; i++) {// 前五行是其他的信息br.readLine();}String createDateLine = br.readLine();StringTokenizer tokenizer = new StringTokenizer(createDateLine);date = tokenizer.nextToken() + " " + tokenizer.nextToken();br.close();// print(date);} catch (IOException e) {log.error("" + e.getMessage());}return date;}/*** 获取文件最后修改时间* * @param filePath*            文件目录*/public static void getLastModifyTime(File filePath) {filePath = new File("\\\\10.131.18.8\\rt3生產機種\\ProductionReprot\\TraceAlterReprot-reprot");File[] list = filePath.listFiles();// for(File file : list){// print(file.getAbsolutePath()+"\tcreate time:"+getCreateTime(file));// }for (File file : list) {Date date = new Date(file.lastModified());print(format(date, "yyyy-MM-dd"));}}public static void getFile() {String root = "\\\\10.131.18.8\\rt3生產機種\\ProductionReprot";File filePath = new File(root);File[] list = filePath.listFiles();for (File file : list) {print(file.getName()+ "\t"+ new File(file.getAbsolutePath() + "\\"+ TUtil.format("yyyy-MM-dd") + ".xls").exists());}}static void test() {String today = TUtil.format("yyyy-MM-dd");String dest = ReadProperties.ReadProprety("server.report.path")+ "TraceAlterReprot-reprot" + "\\" + today + "\\";print(dest);File dir = new File(dest);// 创建当天目录if (!dir.exists()) {dir.mkdir();}}public static void getTimeDifference() {try {Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse("2014-09-15");Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse("2014-09-14");print((d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24);} catch (ParseException e) {e.printStackTrace();}}public List<String> distinctList(List<String> list) {HashSet<String> h = new HashSet<String>(list);list.clear();list.addAll(h);return list;}public List<Object> removeDuplicate(List<Object> list) {HashSet<Object> h = new HashSet<Object>(list);list.clear();list.addAll(h);return list;}/*** 获取四舍五入的整数* @param input 乘数* @param rate 比率* @return 取整后的结果*/public double getRound(int input,double rate){double tmp = input * rate;return Math.round(tmp);}/*** 获取四舍五入的整数* @param input 乘数* @param rate 比率* @return 取整后的结果*/public double ceil(int input,double rate){double tmp = input * rate;return Math.ceil(tmp);}
}

新手个人笔记-java获取Excel模板并生成新的Excel导出相关推荐

  1. 使用java通过固定的excel模板自动生成数据库表的ddl建表语句

    有时候要建很多表或一个表有很多字段,一个个复制字段弄太麻烦了,为了提高点工作效率,写了个小工具通过固定的excel模板自动生成基础的ddl建表语句 maven依赖 <!--核心jar包--> ...

  2. Chimm.Excel —— 使用Java 操作 excel 模板文件生成 excel 文档

    内容已不在此处更新,请移步https://blog.csdn.net/chimmhuang/article/details/111251115 1. 项目介绍 Chimm.Excel 是什么? 该程序 ...

  3. java excel 模板 替换_JAVA POI替换EXCEL模板中自定义标签(XLSX版本)满足替换多个SHEET中自定义标签...

    个人说明:为了简单实现导出数据较少的EXCEL(根据自定义书签模板) 一.替换Excel表格标签方法 ``` /** * 替换Excel模板文件内容 * @param map * 需要替换的标签建筑队 ...

  4. EasyPoi的excel模板预览与下载、导出简单/复杂数据

    官方文档地址:easypoi官网,官方仅供参考,部分描述有问题 excel模板预览 准备工作 事先将整理好的excel模板存在项目中,如图 excel模板预览代码 @GetMapping(" ...

  5. python excel模板 生成excel表格_python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图...

    python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图 #coding=utf-8 from openpyxl importload_workbookfro ...

  6. java word模板poi生成文件_利用poi读取word模板文件生成新的word文档

    利用poi读取word模板文件生成新的word文档 利用poi读取word模板文件,并回填逻辑数据,生成并导出需要的word文档源码.解决模板读取异常问题,提供wordUtils工具类(各种功能实现) ...

  7. Java使用ftl模板文件生成Word,以及Word转换图片或Pdf工具类

    Java使用ftl模板文件生成Word 一.写在前面 最近在项目中使用打印功能,发现这个功能我已经写过多次了,下面这个文章的发步日期在2020年,不得不感慨时间之快啊. https://blog.cs ...

  8. php excel 模板,PHP以Excel模板填充数据并生成新的Excel文件

    遇到这个一个问题,需要生成带水印的Excel文件,具体思路如下:先设置一个调好格式的Excel文件作为模板,再用PHP以模板文件填充,并生成新的Excel文件,这样新的文件就和模板文件格式一致.程序用 ...

  9. 【收藏】Python利用Excel+模板批量生成word文件

    Python利用Excel+模板批量生成word文件 最近帮朋友批量生成小区业主物业费未缴的律师函.朋友那有物业那边的表格数据,包括楼栋-房间号.业主姓名.欠费日期.欠款金额等信息.目的是需要将这些表 ...

最新文章

  1. python rjust() 方法 与 ljust()方法 的使用
  2. 稳扎稳打Silverlight(33) - 3.0控件之AutoCompleteBox, DataPager
  3. 精通Spring Boot——第十一篇:使用自定义配置
  4. Oracle 大规模 delete,update 操作 注意事项
  5. oracle数据库使用之数据查询入门
  6. iOS6和iOS7适应代码(6) —— NSLocalizedString
  7. oracle和mysql数据实时同步_FileYee文件实时同步备份软件,再不怕数据丢失
  8. 原生html如何发送网络请求,原生JS向服务器发送GET请求
  9. Nonlinear Projection Based Gradient Estimation for Query Efficient Blackbox Attacks论文解读
  10. win11开机占用率过高怎么办?win11开机内存占用90%
  11. windows11无法添加朝鲜语输入法
  12. 基于php061在线问卷调查系统
  13. 人脸对齐(一)--定义及作用
  14. linux 截屏_如何在Linux上截图
  15. 《论文阅读》Generating Responses with a Specific Emotion in Dialog
  16. 【Hive】Hive锁机制分析及任务问题处理
  17. 搭建内网音频直播源基于天津相声广播音频
  18. 什么是“高级灰”?哪些地方可以用到它?
  19. 有刷直流电机工作原理详解
  20. zcmu——1601: 卡斯丁狗去挖矿(01背包-三维数组)

热门文章

  1. android ota 方案实战,Android 系统OTA升级流程
  2. 测试员自我提升丨清晰梳理缺陷管理流程
  3. okhttp源码解析(四):重试机制
  4. iec 61508安全标准_成功符合IEC 61508安全标准
  5. Tableau4——标靶图,甘特图,瀑布图
  6. 小啊呜产品读书笔记001:《邱岳的产品手记-08》第15讲 产品案例分析:Mimo与LearnPython的导学之趣 第16讲 在内部产品中找到产品经理的价值
  7. 计算理论期末2022哈工大
  8. 2018年美国国内高校排名
  9. Java每日打卡:第九天
  10. nandflash VS norflash