java导出Excel格式设置
HutoolJava工具类库导出Excel并合并数据,全网最详细!
HutoolJava⼯具类库导出Excel并合并数据,全⽹最详细!ps:基于HuTool⼯具类ExcelWriter合并单元格并且使⽤ jdk1.8 lambda表达式⼀、原始数据模板⼆、合并后的数据按照班级名称、班级分数、⼩组名称、⼩组得分、⼈物名称、⼈物总分进⾏单元格合并合并后效果:三、导⼊依赖ps:pom依赖版本不合适可以换其他版本导出是项⽬中最常见的功能,例如考勤记录导出,账单明细导出,订单记录导出等等。
导出的⼯具类有许多种,⽬前常见的有poi,easypoi,poi...,今天我要说的是基于hutool-poi的导出,hutool-poi是将poi做了封装,简化了⼤量的代码编写。
使⽤⽅式:maven在项⽬的pom.xml中引⼊<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.5.1</version></dependency>gradle在项⽬的build.gradle中引⼊compile 'cn.hutool:hutool-all:5.7.3'四、代码逻辑1.查找数据库返回数据voList;2.设置导出表头数据;3.⽤lambda表达式获取字段分组数据;4.遍历数据,设置合并规则;5.将数据保存在list中;6.ExcelWriter导出excel⽂件五、代码1.需实现将⼈物信息导出到excel⽂件中并且还要按照班级名称,⼩组名称,⼈物名称动态合并单元格,所以先创建⼈物对象:@Data@AllArgsConstructor //⽣成所有参数的构造器public class Person {//班级名称private String className;//班级分数private double classScore;//⼩组名称private String groupName;//⼩组分数private double groupScore;//⼈物姓名private String personName;//⼈物总分private double personScore;//学科名称private String subjectName;//学科分数private double subjectScore;}2.导出核⼼代码:@Slf4j@RestController@RequestMapping("/person")public class PersonController {/*** 将页⾯的数据导出并合并单元格* @param response*/@ApiOperation(value = "导出数据到excel")@ApiImplicitParams({@ApiImplicitParam(name = "response", value = "响应体对象", dataType = "HttpServletResponse")})@GetMapping("/export")public void export(HttpServletResponse response)throws Exception{//1.模拟⼀些⼈物对象数据(⼯作中从数据库查出来)List<Person> list = new ArrayList<>();list.add(new Person("⼀班",90,"⼀组",89,"孙悟空",89,"语⽂",89));list.add(new Person("⼀班",90,"⼀组",89,"孙悟空",89,"数学",98));list.add(new Person("⼀班",90,"⼀组",89,"唐僧",78,"语⽂",98));list.add(new Person("⼀班",90,"⼀组",89,"唐僧",78,"数学",78));list.add(new Person("⼀班",90,"⼆组",90,"沙悟净",90,"语⽂",90));list.add(new Person("⼀班",90,"⼆组",90,"沙悟净",90,"数学",90));list.add(new Person("⼆班",91,"⼀组",97,"鲁智深",98,"语⽂",89));list.add(new Person("⼆班",91,"⼀组",97,"鲁智深",98,"数学",98));list.add(new Person("⼆班",91,"⼆组",89,"宋江",89,"语⽂",98));list.add(new Person("⼆班",91,"⼆组",89,"宋江",89,"数学",78));list.add(new Person("⼆班",91,"⼆组",89,"林冲",88,"语⽂",90));list.add(new Person("⼆班",91,"⼆组",89,"林冲",88,"数学",90));//2.定义基础数据List<String> rowHead = CollUtil.newArrayList("班级名称","班级分数","⼩组名称","⼩组分数","⾓⾊姓名","⾓⾊总分","学科名称","学科分数");//3.通过ExcelUtil.getBigWriter()创建Writer对象,BigExcelWriter⽤于⼤数据量的导出,不会引起溢出;ExcelWriter writer = ExcelUtil.getBigWriter();//4.写⼊标题writer.writeHeadRow(rowHead);ServletOutputStream out = null;//5.实现核⼼逻辑try {//6.定义容器保存⼈物数据List<List<Object>> rows = new LinkedList<>();//7.按照班级进⾏分组LinkedHashMap<String, List<Person>> classList = list.stream().collect(Collectors.groupingBy(item -> item.getClassName(),LinkedHashMap::new, Collectors.toList()));//8.定义起始⾏(⽅便分组后合并时从哪⼀⾏开始)//因为标题已经占了⼀⾏,所以数据从第⼆⾏开始写(excel第⼀⾏索引为0)//因需要合并到⼈物分数单元格所以需定义如下起始坐标int indexClassName = 1; //班级名称起始⾏int indexClassScore = 1;int indexGroupName = 1;int indexGroupScore = 1;int indexPersonName = 1;int indexPersonScore = 1;//9.遍历按班级名分组后的list(⽤entrySet效率⽐keySet效率⾼)for (Map.Entry<String, List<Person>> classNameListEntry : classList.entrySet()) {//10.获取按照班级名分组后的集合List<Person> classValue = classNameListEntry.getValue();//11.计算此集合的长度int classSize = classValue.size();//12.如果只有⼀⾏数据不能调⽤merge⽅法合并数据,否则会报错if (classSize == 1){indexClassName += classSize;indexClassScore += classSize;indexGroupName += classSize;indexGroupScore += classSize;indexPersonName += classSize;indexPersonScore += classSize;}else{//13.根据班级名称进⾏合并单元格//合并⾏,第⼀个参数是合并⾏的开始⾏号(⾏号从0开始),第⼆个参数是合并⾏的结束⾏号,第三个参数是合并的列号开始(列号从0开始), //第四个参数是合并的列号结束,第五个参数是合并后的内容,null不设置,第六个参数指是否⽀持设置样式,true指的是。
java自定义注解在excel导出时的使用
java自定义注解在excel导出时的使用在Java中,自定义注解是一种用于在程序中进行标记的机制。
通过定义自己的注解,可以为类、方法、字段等元素添加元数据,用于描述它们的特性和行为。
在Excel导出时,自定义注解可以用来定义导出的字段和格式,并且可以通过反射机制来读取注解信息,实现自动导出的功能。
下面是一个简单的自定义注解示例:```javaimport ng.annotation.*;String name( default ""; // 导出字段的名称int width( default 20; // 导出字段的宽度String format( default ""; // 导出字段的格式```定义了注解之后,可以在需要导出的类中使用该注解对字段进行标记。
例如:```javapublic class Userprivate String name;private int age;//其他字段和方法...```接下来,可以编写一个用于导出Excel的工具类。
该类可以使用反射来读取类的字段和注解信息,并根据注解信息生成相应的Excel文件。
以下是一个简单的Excel导出工具类示例:```javapublic class ExcelExportUtilpublic static <T> void exportToExcel(List<T> data, Class<T> clazz, String filePath)//创建工作簿和工作表Workbook workbook = new HSSFWorkbook(;Sheet sheet = workbook.createSheet("Sheet1");//获取类的字段和注解信息Field[] fields = clazz.getDeclaredFields(;for (int i = 0; i < fields.length; i++)Field field = fields[i];ExcelField excelField =field.getAnnotation(ExcelField.class);if (excelField != null)//获取注解信息String fieldName = (;int width = excelField.width(;//设置列宽sheet.setColumnWidth(i, width * 256);//创建表头单元格Row headerRow = sheet.getRow(0);if (headerRow == null)headerRow = sheet.createRow(0);}Cell headerCell = headerRow.createCell(i); headerCell.setCellValue(fieldName);}}//创建数据行for (int i = 0; i < data.size(; i++)T item = data.get(i);Row dataRow = sheet.getRow(i + 1);if (dataRow == null)dataRow = sheet.createRow(i + 1);}for (int j = 0; j < fields.length; j++)Field field = fields[j];if (field.isAccessible()try//获取字段值Object value = field.get(item);//创建数据单元格并填充数据Cell dataCell = dataRow.createCell(j); if (value instanceof String) dataCell.setCellValue((String) value); } else if (value instanceof Integer) dataCell.setCellValue((int) value);} else if (value instanceof Double) dataCell.setCellValue((double) value); }} catch (IllegalAccessException e)e.printStackTrace(;}}}}// 保存Excel文件try (FileOutputStream outputStream = newFileOutputStream(filePath))workbook.write(outputStream);} catch (IOException e)e.printStackTrace(;}}```在上面的示例中,exportToExcel方法接收一个泛型列表和类的字节码对象,通过反射来读取类的字段和注解信息,并根据注解信息生成Excel文件。
java实现导出Excel(跨行跨列)
java实现导出Excel(跨行跨列)在Java中,可以使用Apache POI库来实现导出Excel文件,并且可以实现跨行和跨列的功能。
Apache POI是一个开源的Java库,可以处理Microsoft Office格式的文档,包括Excel。
以下是使用Apache POI库实现导出Excel文件的步骤:1. 首先,需要引入Apache POI依赖。
可以在Maven或Gradle中添加以下依赖项:```xml<!-- Apache POI --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>2. 创建一个Workbook对象,该对象代表一个Excel文件:```javaWorkbook workbook = new XSSFWorkbook(;```3. 创建一个Sheet对象,该对象代表Excel文件中的一个工作表:```javaSheet sheet = workbook.createSheet("Sheet1");```4. 创建行和单元格,根据需要设置跨行和跨列的属性。
可以使用CellRangeAddress类来实现跨行和跨列的功能:```javaRow row = sheet.createRow(0);Cell cell = row.createCell(0);cell.setCellValue("跨行跨列");//合并单元格,从第1行到第3行,从第1列到第5列CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 2, 0, 4);sheet.addMergedRegion(cellRangeAddress);5. 将数据写入Excel文件中的单元格:```javaRow row = sheet.createRow(0);Cell cell = row.createCell(0);cell.setCellValue("Hello");```6. 将Workbook对象写入到文件中:```javaFileOutputStream fileOutputStream = new FileOutputStream("output.xlsx");workbook.write(fileOutputStream);fileOutputStream.close(;```完整的示例代码如下所示:```javaimport ermodel.*;import org.apache.poi.ss.util.CellRangeAddress;import ermodel.XSSFWorkbook;import java.io.FileOutputStream;import java.io.IOException;public class ExcelExporterpublic static void main(String[] args) throws IOExceptionWorkbook workbook = new XSSFWorkbook(;Sheet sheet = workbook.createSheet("Sheet1");Row row = sheet.createRow(0);Cell cell = row.createCell(0);cell.setCellValue("跨行跨列");//合并单元格,从第1行到第3行,从第1列到第5列CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 2, 0, 4);sheet.addMergedRegion(cellRangeAddress);FileOutputStream fileOutputStream = newFileOutputStream("output.xlsx");workbook.write(fileOutputStream);fileOutputStream.close(;System.out.println("Excel文件导出成功!");}```执行该代码后,会在项目的根目录下生成一个名为`output.xlsx`的Excel文件,其中包含一个跨行和跨列的单元格。
JAVA实现Excel导入导出以及excel样式设置
JAVA实现Excel导⼊导出以及excel样式设置JAVA实现Excel导⼊/导出以及excel样式设置图2.1 POI的⽬录结构 POI使⽤初步 POI提供给⽤户使⽤的对象在ermodel包中,主要部分包括Excel对象、样式和格式,还有辅助操作等。
最主要的⼏个对象如表3.1所⽰: 表3.1 POI主要对象POI对象名称对应的Excel对象HSSFWorkbook⼯作簿HSSFSheet⼯作表HSSFRow⾏HSSFCell单元格 下⾯我们来看如下的例⼦,使⽤表3.1中的对象在程序的当前⽬录下创建⼀个Excel⽂件test.xls,在第⼀个单元格中写⼊内容,然后读出第⼀个单元格的内容。
完整的程序如下:import ermodel.HSSFWorkbook;import ermodel.HSSFSheet;import ermodel.HSSFRow;import ermodel.HSSFCell;import java.io.FileOutputStream;import java.io.FileInputStream;public class CreateXL{ public static String xlsFile="test.xls"; //产⽣的Excel⽂件的名称 public static void main(String args[]) { try { HSSFWorkbook workbook = new HSSFWorkbook(); //产⽣⼯作簿对象 HSSFSheet sheet = workbook.createSheet(); //产⽣⼯作表对象 //设置第⼀个⼯作表的名称为firstSheet //为了⼯作表能⽀持中⽂,设置字符编码为UTF_16 workbook.setSheetName(0,"firstSheet",HSSFWorkbook.ENCODING_UTF_16); //产⽣⼀⾏ HSSFRow row = sheet.createRow((short)0); //产⽣第⼀个单元格 HSSFCell cell = row.createCell((short) 0); //设置单元格内容为字符串型 cell.setCellType(HSSFCell.CELL_TYPE_STRING); //为了能在单元格中写⼊中⽂,设置字符编码为UTF_16。
java导出excel浏览器直接下载或者或以文件形式导出
java导出excel浏览器直接下载或者或以⽂件形式导出看代码吧~/*** excel表格直接下载*/public static void exportExcelByDownload(HSSFWorkbook wb,HttpServletResponse httpServletResponse,String fileName) throws Exception {//响应类型为application/octet- stream情况下使⽤了这个头信息的话,那就意味着不想直接显⽰内容httpServletResponse.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);//attachment为以附件⽅式下载httpServletResponse.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName + ".xls","utf-8"));/*** 代码⾥⾯使⽤Content-Disposition来确保浏览器弹出下载对话框的时候。
* response.addHeader("Content-Disposition","attachment");⼀定要确保没有做过关于禁⽌浏览器缓存的操作*/httpServletResponse.setHeader("Cache-Control", "No-cache");httpServletResponse.flushBuffer();wb.write(httpServletResponse.getOutputStream());wb.close();}/*** excel以⽂件的形式导出* @throws Exception*/public static void exportExcelByFile(HSSFWorkbook wb,String fileName,String path) throws Exception{ByteArrayOutputStream stream = new ByteArrayOutputStream();wb.write(stream);FileOutputStream outputStream = new FileOutputStream(path + fileName);outputStream.write(stream.toByteArray());stream.close();outputStream.close();}java查询数据导出excel并返回给浏览器下载效果图:1.点击导出表按钮2.接着就会出现下图3.点击上图中的确定按钮再接着就会出现下图4.点击上图中的保存按钮接着就会出现下图,浏览器下载完成后的提⽰5.打开下载好的⽂件如下图好了,废话不多少,上代码jsp前端代码<div style="height:30px;"><a>时间:</a><input id="startDateConsume" type="text" class="easyui-datebox"> <a>-</a><input id="endDateConsume" type="text" class="easyui-datebox"><a>消费类型:</a><select id="consumesType" name=""><option value="0" selected="selected">所有</option><option value="1">报名费</option><option value="2">酒⽔零⾷类</option></select><a>⽀付状态:</a><select id="conPaymentStatus" name=""><option value="0" selected="selected">所有</option><option value="1">未⽀付</option><option value="2">已⽀付</option></select><a id="btnConsumesSearch" class="easyui-linkbutton"data-options="iconCls:'icon-search'" style="margin-left:10px">查询</a><a>(查询出来的数据可统计)</a><a id="consumesOutExcel" class="easyui-linkbutton" style="" data-options="iconCls:'icon-redo'">导出表</a></div>js前端代码$(function() {//导出excel表$('#consumesOutExcel').on('click',function(){exportExcel();});});function exportExcel() {$.messager.confirm('确认', '确认把该搜索结果导出Excel表格?', function(r) {if (r) {var startTime = $('#startDateConsume').val();var endTime = $('#endDateConsume').val();var consumesType = $('#consumesType').val();var conPaymentStatus = $('#conPaymentStatus').val();$.messager.progress({title : '处理中',msg : '请稍后',});$.messager.progress('close');location.href="web/vip/exportExcel.xlsx?startTime=" rel="external nofollow" +startTime+"&endTime="+endTime+"&consumesType="+consumesType+"&conPaymentStatus="+conPaymentStatus; }});}java后端代码@Controller@RequestMapping("/vip")public class VipController {//⽂件下载:导出excel表@RequestMapping(value = "/exportExcel.xlsx",method = RequestMethod.GET)@ResponseBodypublic void exportExcel(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{//⼀、从后台拿数据if (null == request || null == response){return;}List<VipConsumes> list = null;String startTime = request.getParameter("startTime");String endTime = request.getParameter("endTime");int consumesType = Integer.parseInt(request.getParameter("consumesType"));int conPaymentStatus =Integer.parseInt(request.getParameter("conPaymentStatus"));VipConsumesExample example = new VipConsumesExample();if(consumesType!=0 && conPaymentStatus!=0){example.createCriteria().andTimeBetween(startTime, endTime).andConsumeTypeEqualTo(consumesType).andStatusEqualTo(conPaymentStatus);}else if(consumesType ==0 && conPaymentStatus!=0) {example.createCriteria().andTimeBetween(startTime, endTime).andStatusEqualTo(conPaymentStatus);}else if(consumesType!=0 && conPaymentStatus==0){example.createCriteria().andTimeBetween(startTime, endTime).andConsumeTypeEqualTo(consumesType);}else {example.createCriteria().andTimeBetween(startTime, endTime);}list = this.vipConsumesDao.selectByExample(example);//⼆、数据转成excelrequest.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");response.setContentType("application/x-download");String fileName = "消费记录.xlsx";fileName = URLEncoder.encode(fileName, "UTF-8");response.addHeader("Content-Disposition", "attachment;filename=" + fileName); // 第⼀步:定义⼀个新的⼯作簿XSSFWorkbook wb = new XSSFWorkbook();// 第⼆步:创建⼀个Sheet页XSSFSheet sheet = wb.createSheet("startTimeendTime");sheet.setDefaultRowHeight((short) (2 * 256));//设置⾏⾼sheet.setColumnWidth(0, 4000);//设置列宽sheet.setColumnWidth(1,5500);sheet.setColumnWidth(2,5500);sheet.setColumnWidth(3,5500);sheet.setColumnWidth(11,3000);sheet.setColumnWidth(12,3000);sheet.setColumnWidth(13,3000);XSSFFont font = wb.createFont();font.setFontName("宋体");font.setFontHeightInPoints((short) 16);XSSFRow row = sheet.createRow(0);XSSFCell cell = row.createCell(0);cell.setCellValue("流⽔号 ");cell = row.createCell(1);cell.setCellValue("微信名 ");cell = row.createCell(2);cell.setCellValue("微信订单号");cell = row.createCell(3);cell.setCellValue("消费时间");cell = row.createCell(4);cell.setCellValue("消费类型");cell = row.createCell(5);cell.setCellValue("剩余积分 ");cell = row.createCell(6);cell.setCellValue("新增积分 ");cell = row.createCell(7);cell.setCellValue("扣除积分 ");cell = row.createCell(8);cell.setCellValue("消费⾦额");cell = row.createCell(9);cell.setCellValue("⽀付⽅式");cell = row.createCell(10);cell.setCellValue("⽀付状态 ");cell = row.createCell(11);cell.setCellValue("钱包原始⾦额");cell = row.createCell(12);cell.setCellValue("钱包扣除⾦额");cell = row.createCell(13);cell.setCellValue("钱包剩余⾦额");XSSFRow rows;XSSFCell cells;for (int i = 0; i < list.size(); i++) {// 第三步:在这个sheet页⾥创建⼀⾏rows = sheet.createRow(i+1);// 第四步:在该⾏创建⼀个单元格cells = rows.createCell(0);// 第五步:在该单元格⾥设置值cells.setCellValue(list.get(i).getConsumeId());cells = rows.createCell(1);cells.setCellValue(list.get(i).getName());cells = rows.createCell(2);cells.setCellValue(list.get(i).getOrderNumber());cells = rows.createCell(3);cells.setCellValue(list.get(i).getTime());cells = rows.createCell(4);if (list.get(i).getConsumeType() == 2) {cells.setCellValue("酒⽔零⾷费");} else {cells.setCellValue("报名费");}cells = rows.createCell(5);cells.setCellValue(list.get(i).getIntegral());cells = rows.createCell(6);cells.setCellValue(list.get(i).getIntegralIn());cells = rows.createCell(7);cells.setCellValue(list.get(i).getIntegralOut());cells = rows.createCell(8);cells.setCellValue(list.get(i).getMoney());cells = rows.createCell(9);if (list.get(i).getPayment() == 2) {cells.setCellValue("积分抵现");} else if (list.get(i).getPayment() == 3) {cells.setCellValue("微信⽀付");} else if (list.get(i).getPayment() == 4) {cells.setCellValue("现⾦");} else if (list.get(i).getPayment() == 1) {cells.setCellValue("钱包");}cells = rows.createCell(10);if (list.get(i).getStatus() == 2) {cells.setCellValue("已⽀付");} else if (list.get(i).getStatus() == 1) {cells.setCellValue("未⽀付");}cells = rows.createCell(11);cells.setCellValue(list.get(i).getWalletOriginal());cells = rows.createCell(12);cells.setCellValue(list.get(i).getWalletOut());cells = rows.createCell(13);cells.setCellValue(list.get(i).getWalletSurplus());}try {OutputStream out = response.getOutputStream();wb.write(out);out.close();wb.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
Java树形结构数据生成导出excel文件(转载)
Java树形结构数据⽣成导出excel⽂件(转载) 转载⾃1. 效果2. ⽤法1 String jsonStr = "{\"name\":\"aaa\",\"children\":[{\"name\":\"bbb\",\"children\":[{\"name\":\"eee\"},{\"name\":\"fff\",\"children\":[{\"name\":\"iii\"},{\"name\":\"jjj\",\"children\":[{\"name\":\"qqq\"},{\"name\":\"ttt\"}]}]},{\"name\":\"www\"}]},{\"name\":\2 Map tree = JSONObject.parseObject(jsonStr, Map.class);3 tree2Excel(tree, "E:\\" + System.currentTimeMillis() + ".xls", "name", "children");3. 源码1package pers.xxx.demo.tree2excel;23import ermodel.HSSFWorkbook;4import ermodel.*;5import ermodel.XSSFWorkbook;67import java.io.Closeable;8import java.io.File;9import java.io.FileOutputStream;10import java.io.IOException;11import java.util.List;12import java.util.Map;1314/**15 * 树形结构数据导出excel⼯具16 * <p>17 * Created by lzy on 2021/2/24 14:0918*/19 @SuppressWarnings("ALL")20public class Tree2ExcelUtil {2122/**23 * 树形结构数据⽣成excel⽂件24 *25 * @param tree 树形数据26 * @param filePath ⽂件路径27 * @return28*/29public static boolean tree2Excel(Map tree, String filePath) {30return tree2Excel(tree, filePath, null, null);31 }3233/**34 * 树形结构数据⽣成excel⽂件35 *36 * @param tree 树形数据37 * @param filePath ⽂件路径38 * @param lableName 标签Key名称39 * @param childrenName ⼦节点Key名称40 * @return41*/42public static boolean tree2Excel(Map tree, String filePath, String lableName, String childrenName) {43if (isBlank(filePath)) {44 System.err.println("⽂件名称不能为空");45return false;46 }47try {48 doSame(tree, lableName, childrenName);49 createExcel(filePath, tree);50return true;51 } catch (IOException e) {52 e.printStackTrace();53 }54return false;55 }5657/**58 * 树形结构数据⽣成Workbook对象59 *60 * @param tree 树形数据61 * @param fileSuf ⽂件后缀,xls/xlsx62 * @return63*/64public static Workbook tree2Worbook(Map tree, String fileSuf) {65return tree2Worbook(tree, fileSuf, null, null);66 }6768/**69 * 树形结构数据⽣成Workbook对象70 *71 * @param tree 树形数据72 * @param fileSuf ⽂件后缀,xls/xlsx73 * @param lableName 标签Key名称74 * @param childrenName ⼦节点Key名称75 * @return76*/77public static Workbook tree2Worbook(Map tree, String fileSuf, String lableName, String childrenName) { 78if (isBlank(fileSuf)) {79 System.err.println("必须指定⽂件后缀");80return null;81 }82try {83 doSame(tree, lableName, childrenName);84return procesData(tree, fileSuf);85 } catch (Exception e) {86 e.printStackTrace();87 }88return null;89 }909192//具体实现9394/**95 * 标识最⼤列96*/97private static int maxCol = 0;98private static String lableName = "lable";99private static String childrenName = "children";100private static final String COL = "col";101private static final String ROW = "row";102private static final String ROW_OFT = "rowOft";103private static final String ROW_SIZE = "rowSize";104105106private static void doSame(Map tree, String lableName, String childrenName) {107if (!isBlank(lableName)) {108 bleName = lableName;109 }110if (!isBlank(childrenName)) {111 Tree2ExcelUtil.childrenName = childrenName;112 }113 coreAlgoCol(tree, 1);114 coreAlgoRow(tree);115 }116117/**118 * 主要算法,计算列的坐标,计算每个节点所占⾏119 *120 * @param tree 数据121 * @param col 递增的列122 * @param trees 把⾼级别向下传递计算递增的⾏⾼123*/124private static void coreAlgoCol(Map tree, int col, Map... trees) {125 tree.put(COL, col);126 Object childrenObj = tree.get(childrenName);127if (childrenObj != null) {128 List<Map> children = (List<Map>) childrenObj;129if (children.size() > 0) {130int size = children.size() * 2 - 1;131 tree.put(ROW_SIZE, size);132int len = trees != null ? trees.length + 1 : 1;133 Map[] arrData = new Map[len];134135if (trees != null && trees.length > 0) {136for (int i = 0; i < trees.length; i++) {137 Map tree1 = trees[i];138 tree1.put(ROW_SIZE, toInt(tree1.get(ROW_SIZE), 1) + size - 1);139 arrData[i] = tree1;140 }141 }142 arrData[len - 1] = tree;143for (Map tree1 : children) {144int newCol = col + 1;145if (newCol > maxCol) {146 maxCol = newCol;147 }148 coreAlgoCol(tree1, newCol, arrData);149 }150 }151 }152 }153154/**155 * 主要算法,计算⾏的坐标156 *157 * @param tree158*/159private static void coreAlgoRow(Map tree) {160if (toInt(tree.get(ROW)) == 0) {161 tree.put(ROW, Math.round(toInt(tree.get(ROW_SIZE), 1) / 2.0f));162 }163 Object childrenObj = tree.get(childrenName);164if (childrenObj != null) {165 List<Map> children = (List<Map>) childrenObj;166if (children.size() > 0) {167int tempOft = toInt(tree.get(ROW_OFT));168for (Map tree1 : children) {169int rowSize = toInt(tree1.get(ROW_SIZE), 1);170 tree1.put(ROW_OFT, tempOft);171 tree1.put(ROW, tempOft + Math.round(rowSize / 2.0f));172 tempOft += rowSize + 1;173 coreAlgoRow(tree1);174 }175 }176 }177 }178179/**180 * 创建excel⽂件181 *182 * @param filePath ⽂件路径,具体路径到⽂件名183 * @param tree 数据184 * @throws IOException185*/186private static void createExcel(String filePath, Map tree) throws IOException {187 File file = new File(filePath);188boolean bfile = file.createNewFile();189// 复制模板到新⽂件190if (bfile) {191 Workbook wk = procesData(tree, filePath);192if (wk != null) {193 FileOutputStream fos = null;194try {195 fos = new FileOutputStream(file);196 wk.write(fos);197198 fos.flush();199 } finally {200 closeStream(fos);201 wk.close();202 }203 }204 }205 }206207208/**209 * 处理excel数据210 *211 * @param tree 数据212 * @return⼯作表对象213*/214private static Workbook procesData(Map tree, String fileName) {215216 Workbook wk = null;217if (fileName.endsWith("xls")) {218 wk = new HSSFWorkbook();219 }220if (fileName.endsWith("xlsx")) {221 wk = new XSSFWorkbook();222 }223if (wk == null) {224 System.err.println("⽂件名称不正确");225return null;226 }227228//创建⼀个sheet页229 Sheet sheet = wk.createSheet("Sheet1");230231int colSize = maxCol * 2 + 2;232int rowSize = toInt(tree.get(ROW_SIZE), 1);233for (int i = 0; i <= rowSize; i++) {234 Row row = sheet.createRow(i);235for (int j = 0; j <= colSize; j++) {236 row.createCell(j);237 }238 }239//配置单元格背景⾊240 CellStyle style1 = wk.createCellStyle();241 style1.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());242 style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);243 CellStyle style2 = wk.createCellStyle();244 style2.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());245 style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);246247 dealCell(sheet, tree, style1, style2);248249return wk;250 }251252/**253 * 根据计算好的坐标填充每⼀个单元格254 *255 * @param sheet #256 * @param tree 数据257 * @param style1 单元格格式258 * @param style2 单元格格式259*/260private static void dealCell(Sheet sheet, Map tree, CellStyle style1, CellStyle style2) { 261 Row row = sheet.getRow(toInt(tree.get(ROW)));262int oftCol = (toInt(tree.get(COL)) - 1) * 2 + 1;263 Cell cell = row.getCell(oftCol);264 cell.setCellStyle(style1);265 cell.setCellValue(String.valueOf(tree.get(lableName)));266267 sheet.setColumnWidth(oftCol, 256 * 20);268269 Object childrenObj = tree.get(childrenName);270if (childrenObj != null) {271 List<Map> children = (List<Map>) childrenObj;272if (children.size() > 0) {273int size = children.size();274275int startRow = toInt(children.get(0).get(ROW));276int endRow = toInt(children.get(size - 1).get(ROW));277int col = oftCol + 1;278 sheet.setColumnWidth(col, 256);279for (; startRow <= endRow; startRow++) {280 sheet.getRow(startRow).getCell(col).setCellStyle(style2);281 }282283for (Map child : children) {284 dealCell(sheet, child, style1, style2);285 }286 }287 }288 }289290private static int toInt(Object val) {291return toInt(val, 0);292 }293294private static int toInt(Object val, Integer defVal) {295try {296return Integer.parseInt(String.valueOf(val));297 } catch (NumberFormatException ignored) {298 }299return defVal;300 }301302private static boolean isBlank(String str) {303return str == null || str.trim().length() == 0;304 }305306/**307 * 关闭流308 *309 * @param closeables 不定长数组流对象310*/311public static void closeStream(Closeable... closeables) {312for (Closeable closeable : closeables) {313if (closeable != null) {314try {315 closeable.close();316 } catch (IOException e) {317 e.printStackTrace();318 }319 } 320 } 321 }322323 }。
java导出百万级数据到excel
java导出百万级数据到excel最近修改了⼀个导出员⼯培训课程的历史记录(⼀年数据),导出功能本来就有的,不过前台做了时间限制(只能选择⼀个⽉时间内的),还有⼀些必选条件,导出的数据⾮常有局限性。
⼼想:为什么要做出这么多条件限制呢?条件限制⽆所谓了,能限制导出数据的准确性,但是时间?如果我想导出⼀年的数据,还要⼀⽉⼀⽉的去导出,这也太扯了。
于是我试着放开时间js限制,让⽤户⾃⼰随便选好了,然后⾃⼰选了⼀段时间,选了⼏门课程,点击按钮导出,MD报错了,看后台⽇志说什么IO流报异常,看了下代码,代码也很简单,查询数据,⽤HSSFWorkbook 写⼊数据,关闭流,导出,似乎没什么问题。
于是去把查询的sql拉出来,放⼊数据库,查询数据,20w条数据,好吧,这下终于知道为什么加时间限制了,数据量过⼤程序处理不了,改代码吧。
虽说实际⼯作中很少有百万数据导⼊excel,但不缺少⼀些会excel的⾼⼿,分析对⽐数据,像我这种⼿残党是不⾏,他们怎么⽤暂时不⽤管,能不能实现,就是我们应该考虑的事了。
此案例能解决2个问题:1.⽤户导出速度过慢2.采⽤分页导出,以解决单个sheet页数据量过⼤,打开速度过慢简单介绍下我的操作:HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls,⼀张表最⼤⽀持65536⾏数据,256列,也就是说⼀个sheet页,最多导出6w多条数据XSSFWorkbook:是操作Excel2007-2010的版本,扩展名是.xlsx对于不同版本的EXCEL⽂档要使⽤不同的⼯具类,如果使⽤错了,会提⽰如下错误信息。
org.apache.poi.openxml4j.exceptions.InvalidOperationExceptionorg.apache.poi.poifs.filesystem.OfficeXmlFileException它的⼀张表最⼤⽀持1048576⾏,16384列,关于两者介绍,对下⾯导出百万数据很重要,不要使⽤错了!2.SXSSFWorkbook使⽤⽅法和 HSSFWorkbook差不多,如果你之前和我⼀样⽤的HSSFWorkbook,现在想要修改,则只需要将HSSFWorkbook改成SXSSFWorkbook即可,下⾯有我介绍,具体使⽤也可参考。
java批量导出excel格式数据(含每条数据的附件)
,批量导出数据到excel中(包含每条数据对应的附件)本程序功能功能说明采用压缩的方法把用户要导出的excel 文件和excle数据中每条数据对应的文件,打包成一个大文件,输出到缓存区,用户通过浏览器来下载这个文件,缺陷是文件过大时,比如几个G大小的附件,ie下载很慢。
建议用360等支持断点续传的功能的浏览器来下载。
Excel查看附件采用的是链接方式详细如下面截图,点击文件链接,可以链接到相对文件位置的文件夹(因为附件可能是多个,采用的都是文件夹的相对链接的方式实现的),压缩包内存放的文件结构:Excel文件,reportfile(存放附件的文件夹,文件夹结构详细见代码)每行excel 都对应相对的文件夹(reportfile内的某一个子文件夹和excel的行号相对应),如下截图,红色圈圈链接的就是对应的相应文件夹下的appfile文件夹下的文件://引入的类import org.apache.tools.zip.ZipEntry;//把文件写入到压缩对象outimport org.apache.tools.zip.ZipOutputStream;import java.io.*;import java.io.OutputStream;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import ermodel.HSSFCell;import ermodel.HSSFCellStyle;import ermodel.HSSFFont;import ermodel.HSSFRichTextString;import ermodel.HSSFRow;import ermodel.HSSFSheet;import ermodel.HSSFWorkbook;import org.apache.poi.hssf.util.HSSFCellUtil;import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.hssf.util.Region;import ermodel.Font;import ermodel.HSSFHyperlink;//写入压缩的文件对象privatevoid zipfileinfo(ZipOutputStream out, File f, String base) throws Exception{//记录文件“f”对象在压缩包中的位置及压缩后的文件名称:out.putNextEntry(new ZipEntry(base));、// 写入压缩文件对象FileInputStream in = new FileInputStream(f);int b = 0;byte[] buf = newbyte[1024];while ((b = in.read(buf)) != -1){out.write(buf, 0, b);}in.close();}// 开始压缩文件privatevoid ziptmpfilelist(ZipOutputStream out, String factfielnamelist,String tmpfielnamelist) throws Exception {String[] tmpList = tmpfielnamelist.split(";");String[] fackList = factfielnamelist.split(";");for (int i = 0; i<tmpList.length; i++) {File tmpfile = new File(fackList[i]);zipfileinfo(out, tmpfile, tmpList[i].replaceAll("\\\\", "/"));}}@Overrideprotectedvoid doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 存放文件的实际位置位置(绝对路径)String factfielnamelist="D:\\iscm\\attachdata\\2015\\0422\\FuaiFugQArVTjpG;D:\\iscm\\a ttachdata\\2015\\0422\\HIxtANutsZrwDTZ;D:\\iscm\\attachdata\\2 015\\0422\\HIxtANutsZrwDTZ";// 存放文件的位置(绝对路径)压缩时对应文件在压缩文件中的位置及名称String tmpfielnamelist = "reportfile\\tmp1\\appfile\\项目审批2.ipa;reportfile\\tmp1\\appfile\\项目审批1.doc;reportfile\\tmp1\\selffile\\app.docx";try {// 存放临时文件的目录(绝对路径)ZipOutputStream out = new ZipOutputStream(new FileOutputStream("d:\\test.zip"));response.reset();response.setContentType("application/octet-stream");response.setHeader("Content-Disposition","attachment;filename=test.zip");// 输出到缓存区方式ZipOutputStream out = newZipOutputStream(response.getOutputStream());// out.setEncoding("gbk");out.setEncoding("gb2312");//System.out.println(zipFileName);ziptmpfilelist(out, factfielnamelist, tmpfielnamelist);//输出到excel中 List<LinkedHashMap<String, Object>> result 是excel 写入的数据集合,这个需要自己重新定义.ExportExcelUtils.exportExcelAppReoort("App报备信息", headers, columns,result, "", out);out.close();} catch (Exception e) {e.printStackTrace();}}创建excel对象并写入压缩包方法/*** 控制点导出Excel的方法* @param title excel中的sheet名称* @param headers 表头* @param columns 表头对应的数据库中的列名* @param result 结果集* @param out 输出流* @param pattern 时间格式* @throws Exception*/publicstaticvoid exportExcelAppReoort(String title, String[] headers, String[] columns, List<LinkedHashMap<String, Object>> result, String filepath, ZipOutputStream out) throws Exception{//java.io.FileOutputStream out=newjava.io.FileOutputStream(filepath);// 声明一个工作薄HSSFWorkbook workbook = new HSSFWorkbook();// 生成一个表格HSSFSheet sheet = workbook.createSheet(title);// 设置表格默认列宽度为20个字节sheet.setDefaultColumnWidth(20);// 生成一个样式HSSFCellStyle style = workbook.createCellStyle();// 设置这些样式style.setFillForegroundColor(HSSFColor.GOLD.index);style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setBorderTop(HSSFCellStyle.BORDER_THIN);style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 生成一个字体HSSFFont font = workbook.createFont();font.setColor(HSSFColor.VIOLET.index);//font.setFontHeightInPoints((short) 12);font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 把字体应用到当前的样式style.setFont(font);// 指定当单元格内容显示不下时自动换行style.setWrapText(true);// 产生表格标题行HSSFRow row1 = sheet.createRow(0);// sheet.addMergedRegion(new CellRangeAddress(1,2,3,4));//合并单元格sheet.addMergedRegion(new Region(0,(short)0,0,(short)19));row1.setHeight((short)600); //设置行高度HSSFCell cell1 = row1.createCell(0);cell1.setCellStyle(style);cell1.setCellValue(title); //"App报备信息"HSSFRow row = sheet.createRow(1);for (int i = 0; i<headers.length; i++) {HSSFCell cell = row.createCell(i);cell.setCellStyle(style);HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text);}// 遍历集合数据,产生数据行if(result != null){int index = 2;for(LinkedHashMap<String, Object> m:result){row = sheet.createRow(index);int cellIndex = 0;for(String s:columns){HSSFCell cell = row.createCell(cellIndex);//cell.setCellStyle(style2);HSSFRichTextStringrichString = new HSSFRichTextString(m.get(s) == null ? "" : m.get(s).toString());if(s.equals("appAttr") || s.equals("threeSynAttr") ){//当前记录记录附件链接的文件夹位置(文件可能多个,如果一个的话,可以自己处理直接链接指向文件)String tmp=richString.toString();if (!(richString.toString().equals(""))){cell.setCellValue("文件链接");HSSFHyperlink link =new HSSFHyperlink(HSSFHyperlink.LINK_URL);link.setAddress(richString.toString());cell.setHyperlink(link);}}else{if(cellIndex==0)cell.setCellValue(Integer.valueOf(m.get(s).toString()));elsecell.setCellValue(richString);}cellIndex++;}index++;}}//写入压缩包out.putNextEntry(new ZipEntry("appReport.xls"));workbook.write(out); //写入文件}。
java,poi导出excel表格为数字格式
java,poi导出excel表格为数字格式篇一:POI设置EXCEL单元格格式为文本实际开发过程中通常用到的就是从数据库导出EXCEL 表格了,JXL可以这样做,其实POI也可以(关于JXL与POI的异同可访问我之前总结的文章),之前写过POI对七种文档(当然也包括EXCEL)的内容读取操作的文章,这次要写的就非常重要了,就是开发中经常会用到的POI读取数据库导出EXCEL的操作,所谓导出EXCEL也就是生成带数据内容的新的EXCEL文件目前的POI版本是3.7下载地址:/download.html#POI-3.7 必须包只有一个:poi-3.7-20101029.jar整理思路:1)数据库中的字段对应EXCEL的最顶层一行各个CELL名称[也就是上面图片中序号版本...的]2)将每个数据一次插入到对应名称CELL的对应记录位置3)为了方便操作,顶层的cell各个名称可以抽取出来成为一个单独类具体代码第一部分:单独的EXCEL表头类 public class Cachetable {Java代码1. // Fields2. private int recnum;3. private String devIp;4. private String srcaddr;5. private String dstaddr;6. private String nexthop;7. private String input;8. private String output;9. private String dpkts;10.private String doctets;11.private String sstart;12.13.private String dstport;14.private String prot;15.private String tos;16.private String srcas;17.private String dstas;18.private String pduversion;19.20.21./** default constructor */22.public Cachetable() {23.}24.25.26./** full constructor */27.public Cachetable(int recnum, String devIp, String srcaddr, String dstaddr, String nexthop, String input, String output, String dpkts, String doctets, String sstart, String dstport, String prot, String tos, String srcas, String dstas,String pduversion) {28. this.recnum = recnum;29. this.devIp = devIp;30. this.srcaddr = srcaddr;31. this.dstaddr = dstaddr;32. this.nexthop = nexthop;33. this.input = input;34. this.output = output;35. this.dpkts = dpkts;36. this.doctets = doctets;37. this.sstart = sstart;38. this.dstport = dstport;39. this.prot = prot;40. this.tos = tos;41. this.srcas = srcas;42. this.dstas = dstas;43. this.pduversion = pduversion;44.45.}46.47.48.public int getRecnum() {49. return this.recnum;50.}51.52.public void setRecnum(int recnum) {53. this.recnum= recnum;54.}56.public String getDevIp() {57. return this.devIp;58.}60.public void setDevIp(String devIp) {61. this.devIp = devIp;62.}63.64.65.public String getSrcaddr() {66. return this.srcaddr;67.}68.69.public void setSrcaddr(String srcaddr) {70. this.srcaddr = srcaddr;71.}72.73.74.public String getDstaddr() {75. return this.dstaddr;76.}77.78.public void setDstaddr(String dstaddr) {79. this.dstaddr = dstaddr;80.}82.83.public String getNexthop() {84. return this.nexthop;85.}86.87.public void setNexthop(String nexthop) {88. this.nexthop = nexthop;89.}90.91.92.public String getInput() {93. return this.input;94.}95.96.public void setInput(String input) {97. this.input = input;98.}100.101.102.103.105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142. public String getOutput() { return this.output; } public void setOutput(String output) { this.output = output; } public String getDpkts() { return this.dpkts; } public void setDpkts(String dpkts) { this.dpkts = dpkts; } public String getDoctets() { return this.doctets; } public void setDoctets(String doctets) { this.doctets = doctets; }public String getSstart() { return this.sstart; } public void setSstart(String sstart) { this.sstart = sstart; } public String getDstport() { return this.dstport; } public void setDstport(String dstport) { this.dstport = dstport; } 143. public String getProt() {144. return this.prot;145. }146.147. public void setProt(String prot) {148. this.prot = prot;149. }150.151.152. public String getT os() {153. return this.tos;154. }155.156. public void setT os(String tos) {157. this.tos = tos;158. }159.160. public String getSrcas() {161. return this.srcas;162. }163.164. public void setSrcas(String srcas) {165. this.srcas = srcas;166. }167.168.169. public String getDstas() {170. return this.dstas;171. }172.173. public void setDstas(String dstas) {174. this.dstas = dstas;175. }176.177. public String getPduversion() {178. return this.pduversion;179. }180.181. public void setPduversion(String pduversion) { 182. this.pduversion = pduversion;183. }184.185.篇二:java导出excel表格代码package document.poi.excel;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Date;import ermodel.HSSFCell;import ermodel.HSSFCellStyle;import ermodel.HSSFDataFormat; import ermodel.HSSFDateUtil;import ermodel.HSSFRichT extString;import ermodel.HSSFRow;import ermodel.HSSFSheet;import ermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor;public class T estExcel {/*** HSSFWorkbook excell的文档对象HSSFSheet excell的表单HSSFRow excell的行* HSSFCell excell的格子单元HSSFFont excell字体HSSFName 名称HSSFDataFormat 日期格式* HSSFHeader sheet头HSSFFooter sheet尾HSSFCellStyle cell样式*/public static void main(String[] args) throws IOException {//新那一个Excel//writeT oBlankExcel();//根据Excel模板,生成文件并导入数据writeT oExcelT emplet();}/*** 新建excel* @throws IOException*/public static void writeT oBlankExcel() throws IOException{HSSFWorkbook wb = new HSSFWorkbook();// 建立新HSSFWorkbook对象HSSFSheet sheet = wb.createSheet(new sheet);// 建立新的sheet对象// Create a row and put some cells in it.Rows are 0 based. HSSFRow row = sheet.createRow((short) 0);// 建立新行// Create a cell and put a value in it.HSSFCell cell = row.createCell(0); //row.createCell(0);// 建立新cellcell.setCellValue(1222);// 设置cell的整数类型的值// Or do it on one line.row.createCell(1).setCellValue(1.2);// 设置cell浮点类型的值row.createCell(2).setCellValue(test);// 设置cell字符类型的值row.createCell(3).setCellValue(true);// 设置cell布尔类型的值HSSFCellStyle cellStyle = wb.createCellStyle();// 建立新的cell样式cellStyle.setDataFormat(HSSFDataFormat.getBuiltinForma t(m/d/yy h:mm));// 设置cell样式为定制的日期格式HSSFCell dCell = row.createCell(4);dCell.setCellValue(new Date());// 设置cell为日期类型的值dCell.setCellStyle(cellStyle);// 设置该cell日期的显示格式HSSFCell csCell = row.createCell(5);//csCell.setEncoding(HSSFCell.ENCODING_UTF_16);// 设置cell编码解决中文高位字节截断csCell.setCellValue(中文测试_Chinese Words T est);// 设置背景色HSSFCellStyle style = wb.createCellStyle();style.setFillForegroundColor(new HSSFColor.BLACK().getIndex());style.setFillBackgroundColor(new HSSFColor.ROSE().getIndex());style.setFillPattern(HSSFCellStyle.SPARSE_DOTS);HSSFCell cell1 = row.createCell(6);cell1.setCellStyle(style);//cell1.setCellValue(X);//setCellValue 被cell1.setCellValue(new HSSFRichT extString(aaaaaaaaaaaa)); 替换cell1.setCellValue(new HSSFRichT extString(aaaaaaaaaaaa));// 设置背景色HSSFCellStyle style1 = wb.createCellStyle();style1.setFillForegroundColor(new HSSFColor.GREY_40_PERCENT().getIndex());style1.setFil lBackgroundColor(newHSSFColor.GREY_40_PERCENT().getIndex());style1.setBo rderBottom((short) 1);style1.setBorderT op((short) 1);style1.setBorderLeft((short) 1);style1.setBorderRight((short) 1);/*** 注意这句代码,style1.setFillPattern, 如果你在你的程序中不设置fill pattern,那么* 你上面设置的前景色和背景色就显示不出来.网络上很多文章都没有设置fillpattern,* 不知道那些达人的机器是不是比我的机器智能很多. */style1.setFillPattern(HSSFCellStyle.SPARSE_DOTS);HSSFCell cell11 = row.createCell(7);cell11.setCellValue(X11);cell11.setCellStyle(style1);// 数字格式化HSSFCellStyle st = wb.createCellStyle();// 建立新的cell样式st.setDataFormat(HSSFDataFormat.getBuiltinFormat(#,##0 ));HSSFCell cell12 = row.createCell(8);cell12.setCellValue((double) 10000000);cell12.setCellStyle(st);// 设置中西文结合字符串row.createCell(9).setCellType(HSSFCell.CELL_TYPE_ERR OR);// 建立错误cell// Write the output to a fileFileOutputStream fileOut = new FileOutputStream(d:/doc/2_workbook.xls);wb.write(fileOut); fileOut.close();}/*** 导入数据到excel模板中* @throws IOException*/public static void writeT oExcelT emplet() throws IOException{FileInputStream fi = null;HSSFWorkbook hwb = null;HSSFRow row = null;//行HSSFCell cell = null;//列//1,读取Excelfi = new FileInputStream(d:/doc/2_test_excel.xls);hwb = new HSSFWorkbook(fi);//2,取得第一个SheetHSSFSheet sheet = hwb.getSheetAt(0);int rows = sheet.getLastRowNum();//行数, base 0int cols = -1;System.out.println(rows: + (rows+1));for (int i = 0 ; i <= rows ; i++) {//遍历行row = sheet.getRow(i);//取得行cols = row.getLastCellNum();//取得最后一列有序号base 1System.out.print(第[+ (i+1) +]行有[+ (cols) +]列(base 1): );for (int j = 0 ; j < cols ; j++) {//遍历列cell = row.getCell(j);Object value = null;if (null != cell) {switch (cell.getCellType()) {case HSSFCell.CELL_TYPE_NUMERIC: // 数值型if (HSSFDateUtil.isCellDateFormatted(cell)) {//如果是date类型则,获取该cell的date值valueHSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toSt ring();System.out.print(value);}else{//纯数字value = cell.getNumericCellValue() + 1;//数字加一}System.out.print(value);cell.setCellValue((Double)value);break;/* 此行表示单元格的内容为string类型*/case HSSFCell.CELL_TYPE_STRING: // 字符串型value = cell.getRichStringCellValue().toString();System.out.print(value);break;case HSSFCell.CELL_TYPE_FORMULA://公式型=//读公式计算值value = String.valueOf(cell.getNumericCellValue());if(value.equals(NaN)){//如果获取的数据值为非法值,则转换为获取字符串value = cell.getRichStringCellValue().toString();}//cell.getCellFormula();读公式System.out.print(value);break;case HSSFCell.CELL_TYPE_BOOLEAN://布尔value = + cell.getBooleanCellValue();System.out.print(value);break;/* 此行表示该单元格值为空*/case HSSFCell.CELL_TYPE_BLANK: // 空值value = ;System.out.print(value);break;case HSSFCell.CELL_TYPE_ERROR: // 故障value = ;System.out.print(value);break;default:value = cell.getRichStringCellValue().toString();System.out.print(value);}}}System.out.println();}hwb.write(new FileOutputStream(d:/doc/2_test_excel_结果.xls));}}篇三:poi导出excel文件并提示下载一、导入jar包:poi-3.0.1-FINAL-20070705.jar;poi-3.0-alpha1-20050704.jar;二、获取List<bean类型数据三、利用poi生成excel文件/*** 生成excel文件* @param tjxxs 写入excel的List<WorkListBean数据* @param xlsName 文件名称* @param sheetName 内容标题* @return int*/@SuppressWarnings(deprecation)public int resultSetT oExcel(List<WorkListBean tjxxs,String xlsName,String sheetName) throws Exception{if(tjxxs == null || .equals(tjxxs)){return 0;}HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = workbook.createSheet();HSSFRow row= sheet.createRow((short)0);;HSSFCell cell;//写入各个字段的名称for(int i=1;i<=4;i++){cell = row.createCell((short)(0));cell.setCellType(HSSFCell.CELL_TYPE_STRING);ENCODING_UTF_16);序号);cell = row.createCell((short)(1));cell.setCellType(HSSFCell.CELL_TYPE_STRING);ENCODING_UTF_16);工作控制号);//cell = row.createCell((short)(2)); cell.setCellType(HSSFCell.CELL_TYPE_STRING);ENCODING_UTF_16); 单位名称);cell = row.createCell((short)(3));cell.setCellType(HSSFCell.CELL_TYPE_STRING); ENCODING_UTF_16); 工作类型); int iRow=1; //写入各条记录,每条记录对应Excel中的一行for(int i = 0;i < tjxxs.size();i++){ WorkListBean tjxx = tjxxs.get(i); row= sheet.createRow((short)iRow); cell = row.createCell((short)0);cell.setCellType(HSSFCell.CELL_TYPE_STRING); ENCODING_UTF_16); cell.setCellValue(iRow); cell = row.createCell((short)1);cell.setCellType(HSSFCell.CELL_TYPE_STRING); ENCODING_UTF_16); cell = row.createCell((short)2); cell.setCellType(HSSFCell.CELL_TYPE_STRING); ENCODING_UTF_16); cell = row.createCell((short)3); cell.setCellType(HSSFCell.CELL_TYPE_STRING); ENCODING_UTF_16); iRow++; }FileOutputStream fOut = new FileOutputStream(xlsName); FileOutputStream(xlsName);try {workbook.write(fOut);fOut.flush();} catch (Exception e) {e.printStackTrace();}finally {if(fOut != null){fOut.close();}}return 1;}四、设置提示下载弹出框FileInputStream fis = new FileInputStream(new File(file)); OutputStream os = response.getOutputStream();response.setHeader(Content-Disposition,attachment;filename=+newString(fileName.getBytes(gb2312),iso8859-1));response.setCharacterEncoding(utf-8);int j = 0;byte[] b = new byte[8192];while ((j = fis.read(b, 0, 8192)) != -1){os.write(b, 0, j);}os.flush();fis.close();注:fileName.getBytes(gb2312),iso8859-1)是解决文件名中文乱码的问题;详见InitAction和CommonMethod文件中方法;。
java实现导出Excel(跨行,跨列)
java实现导出Excel(跨⾏,跨列)先来个最终结果样式:第⼀步:传参,后期可根据⾃⼰需要进⾏调整。
我这⾥需要的是quarter 代表季度dptid 部门编号根据接受过来的参数进⾏⽂档命名。
UserInfo userInfo=(UserInfo)request.getSession().getAttribute("userInfo");String userid=userInfo.getUserID();String quarter = request.getParameter("quarter");String dptid = request.getParameter("dptid");/***********************EXCEL导出部分**************************/String str3 = FileInfoTools.getSystemFilePath()+ "/documentTemp/";File file = new File(str3);if (!file.exists() && !file.isDirectory()) {file.mkdir();}String names = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date());String ourl = str3 + names + "_"+userid+".xls";FileOutputStream fos = null;String fileName = "";try {HSSFWorkbook wb = new HSSFWorkbook();//创建⼯作薄fileName = "安全可控导出"+"_"+userid+"_"+names+".xls";DBManager dbm = new DBManager();System.out.println("quarter+"+quarter+"dptid="+dptid);try{dbm.newConnection();String str = "select departmentname from dpt_department where departmentid='"+dptid+"'"; //获取唯⼀idString dptName = dbm.executeQueryString(str);fileName=dptName+"部门安全可控清单汇总"+"_"+userid+"_"+names+".xls";//创建sheet页,并写⼊内容createSheet(dbm,wb,getCardInfo(dbm,quarter,dptid));}catch(Exception e){e.printStackTrace();}finally{dbm.closeConnection();}File ff = new File(ourl);if (ff.exists()) {ff.delete();}fos = new FileOutputStream(ourl);wb.write(fos);fos.close();String u = "/project/system/fileAction.do?filePath=" + URLEncoder.encode(ourl)+ "&fileName=" + URLEncoder.encode(fileName);response.sendRedirect(u);} catch (Exception e) {e.printStackTrace();}第⼆步:创建sheet页签public void createSheet(DBManager dbm,HSSFWorkbook w,Vector vt) throws Exception{for(int i=0;i<vt.size();i++){Hashtable ht = (Hashtable)vt.get(i);String id = (String)ht.get("id");String quarter = (String)ht.get("quarter");HSSFSheet sheet = w.createSheet("安全可控清单");//写⼊数据wirteSheet(dbm,sheet,w,id,quarter);}}我这⾥页签是固定的名称可根据⾃⼰的需要根据参数来进⾏判断页签。
关于Java中excel表格导出的总结(Java程序导出模板和Java根据模板导出表格两种。。。
关于Java中excel表格导出的总结(Java程序导出模板和Java根据模板导出表格两种。
导出excel通⽤模板(程序定义模板导出)转载原⽂:如下代码,本⽅法主要⽤于程序定义模板格式,并导出⽂件。
该⽅法将定义和创建分离,达到了⼀定解耦合,降低了开发复杂度。
但是依然是程序定义模板,对模板的样式需要程序控制,没有达到将数据和样式分离的⽬的。
改良版,关于添加依赖之类的之前⼀篇⽂章⾥⾯有。
这篇是把之前的⽅法抽成通⽤模板。
⼀、添加⼀个实体类package com.lencity.securitymanagementplatform.data.entity;import java.util.List;public class XlsData {public static final int DATA_TYPE_INTEGER = 0;public static final int DATA_TYPE_STRING = 1;private List<String> titles;//表头private List<Integer> types;//数据类型private List<List<Object>> values;存表数据public List<Integer> getTypes() {return types;}public void setTypes(List<Integer> types) {this.types = types;}public List<String> getTitles() {return titles;}public void setTitles(List<String> titles) {this.titles = titles;}public List<List<Object>> getValues() {return values;}public void setValues(List<List<Object>> values) {this.values = values;}}⼆、创建⼀个service类package com.lencity.securitymanagementplatform.service;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import .URLEncoder;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import ermodel.HSSFCell;import ermodel.HSSFCellStyle;import ermodel.HSSFDataFormat;import ermodel.HSSFFont;import ermodel.HSSFRow;import ermodel.HSSFSheet;import ermodel.HSSFWorkbook;import ermodel.HorizontalAlignment;import org.springframework.stereotype.Service;import com.lencity.securitymanagementplatform.data.entity.XlsData;@Servicepublic class XlsService {//写⼀个接⼝,哪个控制器需要加上导出excel功能就继承这个接⼝public static interface IXlsOutputProcessor {public XlsData processXlsData(Map<String, Object> condition);}//解析数据创建excelpublic HSSFWorkbook createExcelData(IXlsOutputProcessor processor, Map<String, Object> condition) {XlsData xlsData = processor.processXlsData(condition);HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = workbook.createSheet("统计表");// 创建⼀个excel表单HSSFRow titleRow = sheet.createRow(0);// 设置列宽,setColumnWidth的第⼆个参数要乘以256,这个参数的单位是1/256个字符宽度sheet.setColumnWidth(1, 15 * 256);sheet.setColumnWidth(3, 20 * 256);HSSFCellStyle style = workbook.createCellStyle();style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));// 设置⽇期格式HSSFFont font = workbook.createFont();// 设置为居中加粗font.setBold(true);style.setAlignment(HorizontalAlignment.CENTER);style.setFont(font);List<String> titles = xlsData.getTitles();HSSFCell cell;/* 构造表头 */for (int i = 0; i < titles.size(); i++) {cell = titleRow.createCell(i);cell.setCellValue(titles.get(i));cell.setCellStyle(style);}int rowNum = 1;List<Integer> dataTypes = xlsData.getTypes();List<List<Object>> values = xlsData.getValues();for (int i = 0; i < values.size(); i++) {List<Object> value = values.get(i);HSSFRow row = sheet.createRow(rowNum);for (int j = 0; j < value.size(); j++) {switch (dataTypes.get(j)) {case XlsData.DATA_TYPE_INTEGER:row.createCell(j).setCellValue((Integer) value.get(j));break;case XlsData.DATA_TYPE_STRING:row.createCell(j).setCellValue((String) value.get(j));break;}}rowNum++;}return workbook;}// 浏览器导出excelpublic void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response)throws Exception {response.reset();response.setContentType("application/vnd.ms-excel");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8")); OutputStream outputStream = response.getOutputStream();workbook.write(outputStream);outputStream.flush();outputStream.close();}// 下载excel模板功能public void downloadTemplate(HttpServletResponse response,HttpServletRequest request) throws Exception {String fileName="导出模板.xls";response.reset();response.setContentType("application/vnd.ms-excel");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); String filePath=request.getServletContext().getRealPath("/excel/")+fileName;FileInputStream input=new FileInputStream(filePath);OutputStream out=response.getOutputStream();byte[] b=new byte[2048];int len;while((len=input.read(b))!=-1) {out.write(b,0,len);}response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));input.close();}}三、控制器假设我们要在⽤户页⾯加上导出表格的功能,那就在⽤户的控制器上继承接⼝public class UserController implements IXlsOutputProcessor {继承之后需要在控制器中重写接⼝⽅法,导出的表格样式.png关于封装数据,主要就是根据⾃⼰实际的项⽬需求,来构造数据了// 封装数据@Overridepublic XlsData processXlsData(Map<String, Object> condition) {List<String> titles = new ArrayList<>();//表头List<Integer> dataTypes = new ArrayList<>();//表数据类型List<List<Object>> values = new ArrayList<>();//表头对应的数据titles.add("姓名");dataTypes.add(XlsData.DATA_TYPE_STRING);titles.add("⼿机号码");dataTypes.add(XlsData.DATA_TYPE_STRING);titles.add("职位");dataTypes.add(XlsData.DATA_TYPE_STRING);titles.add("部门");dataTypes.add(XlsData.DATA_TYPE_STRING);List<User> users = userService.getUsersByCondition(condition);XlsData xlsData = new XlsData();xlsData.setTitles(titles);xlsData.setTypes(dataTypes);for (User user : users) {List<Object> tmpList = new ArrayList<>();tmpList.add(user.getName());tmpList.add(user.getMobile());tmpList.add(user.getPosition());tmpList.add(departmentService.getDepartmentNameByDepartmentCode(user.getDepartmentCode()));values.add(tmpList);}xlsData.setValues(values);return xlsData;}// 导出excel,前台js,点击导出excel 关联的路径就是这个@PostMapping(value = "/downLoadXls")@ResponseBodypublic String downLoadXls(Map<String, Object> condition, HttpServletResponse response) throws Exception { String fileName = "导出excel.xls";HSSFWorkbook workbook = xlsService.createExcelData(this, condition);xlsService.buildExcelDocument(fileName, workbook, response);JSONObject jsonObject = new JSONObject();jsonObject.put("code", 1);return jsonObject.toString();}// 下载模板,前台js,点击下载模板关联的路径就是这个@PostMapping(value = "/downloadTemplate")@ResponseBodypublic String downloadTemplate(HttpServletResponse response,HttpServletRequest request) throws Exception { String fileName = "导出excel.xls";xlsService.downloadTemplate(response, request);JSONObject jsonObject = new JSONObject();jsonObject.put("code", 1);return jsonObject.toString();}前台界⾯.png模板的存放位置前台按钮代码<button type="button" class="btn btn-primary waves-effect" onclick="downloadTemplate()" id="downloadTemplate"><i class="material-icons">vertical_align_bottom</i><span>下载模板</span></button><button type="button" class="btn btn-primary waves-effect"onclick="exportExcel()"><i class="material-icons">vertical_align_bottom</i><span>导出表格</span></button>jsform表单⾥⾯是页⾯的表单筛选条件,如果要导数据库所有的数据,可把form表单去掉。
java 导出 freemarker excel 集合实例-概述说明以及解释
java 导出freemarker excel 集合实例-概述说明以及解释1.引言文章1.1 概述部分的内容可以写作如下:Java是一种广泛使用的编程语言,而Excel作为一种常用的办公软件,经常使用于数据分析和报表生成等领域。
在实际开发中,我们经常需要将Java中的数据导出到Excel中进行展示或者进一步处理。
然而,Java自身并没有提供直接将数据导出为Excel的功能。
为了实现这个需求,我们可以借助第三方库Freemarker来进行Excel的导出。
Freemarker是一款模板引擎,它可以将Java中的数据与预先定义好的Excel模板文件进行结合,生成最终的Excel报表。
本文将介绍如何使用Java和Freemarker来实现Excel的导出功能。
首先,我们将探讨Java导出Excel的需求,了解在实际项目中我们可能会遇到的问题和要求。
接下来,我们将详细介绍如何使用Freemarker来实现Excel导出功能,并提供一些实例代码供读者参考。
通过本文的学习,读者将能够掌握使用Java和Freemarker导出Excel 的基本原理和方法,为以后类似需求的项目开发提供参考。
同时,我们也将对导出功能的局限性进行讨论,并展望未来可能的改进方向。
接下来,我们将开始探讨Java导出Excel的需求。
文章结构部分的内容:文章结构是指文章的组织架构和章节分布,它的设计直接影响读者对文章内容的理解和阅读体验。
本文将按照以下方式组织结构和分布各章节内容:1. 引言部分:1.1 概述:介绍本文主题以及所讨论的问题的背景和重要性。
说明Java导出FreeMarker Excel集合实例的意义和应用场景。
1.2 文章结构:本章节。
详细说明文章的整体框架和组织结构,以便读者能清晰地了解文章的逻辑和内容安排。
1.3 目的:明确本文的目标和目的,阐述我们要达到的效果和希望读者能够得到的收获。
2. 正文部分:2.1 Java导出Excel的需求:解释为什么我们需要在Java中进行Excel导出操作,列举一些具体的应用场景和需求案例。
java实现数据的Excel导出,自定义导出字段,转换字典值
java实现数据的Excel导出,⾃定义导出字段,转换字典值第⼀版代码:基础功能跳转此⽂章:简介新增功能:1. 添加⾃定义字段导出功能, ⽤户可以选择字段进⾏导出2. 将字典类型数据进⾏转换(如:0=⼥,1=男, 将0转换为⼥, 1转换为男)3. 添加表头格式4. 随机⽂件名称, 防⽌多次导出时⽂件覆盖问题实现代码Excel注解@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface Excel {/*** 导出到Excel中的名字*/String name() default "";/*** ⽇期格式, 如: yyyy-MM-dd*/String dateFormat() default "";/*** 字典的key值*/String dictKey() default "";/*** 读取内容转表达式 (如: 0=男,1=⼥,2=未知)*/String dictExp() default "";}123456789101112131415161718192021222324public class ExcelUtil<T> {/*** ⼯作薄*/private Workbook wb;/*** ⼯作表*/private Sheet sheet;/*** 需要导出的数据*/private List<T> exportList;/*** 对象的class对象*/private Class<T> clazz;/*** 被选中需要导出的字段名称*/private Map<String, Object> checkedFieldsName;/*** 被选中需要导出的字段对象*/private List<Field> checkedFields;/*** 包含需要字典转换的字段对象*/private List<Field> fieldsContainDict;/*** 对象中的字典值*/private Map<String, Map<String, String>> dicts;private ExcelUtil(){}public ExcelUtil(Class<T> clazz){this.clazz = clazz;}/**** @param list* @param sheetName* @param fieldsName*/public void exportExcel(List<T> list, Map<String, Object> fieldsName, String sheetName){ // 初始化数据init(list, sheetName, fieldsName);// 转换字典值try {convertDict();} catch (IllegalAccessException e) {e.printStackTrace();}// sheet第⼀⾏加⼊名称数据createTopRow();// sheet其他⾏,添加⽬标数据try {createOtherRow();} catch (IllegalAccessException e) {e.printStackTrace();}// 导出wbtry(OutputStream outFile = new FileOutputStream(generateFileName())){wb.write(outFile);} catch (IOException e) {e.printStackTrace();}}}/*** 添加导出数据*/private void createOtherRow() throws IllegalAccessException {for (int rowNum = 1; rowNum <= exportList.size(); rowNum++) {Row row = sheet.createRow(rowNum);T t = exportList.get(rowNum - 1);for (int colNum = 0; colNum < checkedFields.size(); colNum++) {Cell cell = row.createCell(colNum);Field field = checkedFields.get(colNum);field.setAccessible(true);// 单元格设置值addCell(cell, field, t);}}}/*** 单元格中添加数据** @param cell 单元格* @param field 字段* @param t list中的⼀条数据*/private void addCell(Cell cell, Field field, T t) throws IllegalAccessException {Class<?> fieldType = field.getType();if (String.class == fieldType) {cell.setCellValue((String) field.get(t));} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {cell.setCellValue((Integer) field.get(t));} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {cell.setCellValue((Long) field.get(t));} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {cell.setCellValue((Double) field.get(t));} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {cell.setCellValue((Float) field.get(t));} else if (Date.class == fieldType) {String dateFormat = field.getAnnotation(Excels.class).dateFormat();cell.setCellValue(dateFormat((Date) field.get(t), dateFormat));}}/*** 时间格式转换* @param date ⽇期* @param dateFormat ⽇期格式* @return*/private String dateFormat(Date date, String dateFormat) {if (dateFormat == null || "".equals(dateFormat)) {dateFormat = "yyyy-MM-dd HH:mm:ss";}SimpleDateFormat df = new SimpleDateFormat(dateFormat);return df.format(date);}/*** sheet第⼀⾏加⼊名称数据*/private void createTopRow() {Row row = sheet.createRow(0);Map<String, CellStyle> styles = createStyles(wb);for (int index = 0; index < checkedFields.size(); index++) {Cell cell = row.createCell(index);cell.setCellValue(checkedFields.get(index).getAnnotation(Excels.class).name()); System.out.println(styles.get("header"));cell.setCellStyle(styles.get("header"));}}private void convertDict() throws IllegalAccessException {for (Field field : fieldsContainDict) {Excels annotation = field.getAnnotation(Excels.class);String dictKey = annotation.dictKey();field.setAccessible(true);for (T t : exportList) {// 获取字段值String o = (String) field.get(t);field.set(t, dicts.get(dictKey).get(o));}}}/*** 将数据导出Excel** @param list 需要导出的数据* @param sheetName ⼯作表名称*/public void exportExcel(List<T> list, String sheetName){exportExcel(list, null, sheetName);}/*** 将数据导出Excel** @param list 需要导出的数据*/public void exportExcel(List<T> list) {exportExcel(list, null, "sheet");}/*** 初始化*/public void init(List<T> list ,String sheetName, Map<String, Object> fieldsName){ this.checkedFieldsName = fieldsName;this.exportList = list;// 初始化导出数据initExportList();// 初始化⼯作薄initWorkbook();// 初始化⼯作表initSheet(sheetName);// 初始化checkedFields, fieldsContainDictinitFields();// 根据注解⽣成⽣成字典generateObjDict();}/*** 初始化导出数据*/private void initExportList(){// 防⽌导出过程中出现空指针if(Objects.isNull(this.exportList)) {this.exportList = new ArrayList<>();}}/*** 初始化⼯作簿*/private void initWorkbook(){this.wb = new SXSSFWorkbook();}/*** 初始化⼯作表*/private void initSheet(String sheetName){this.sheet = wb.createSheet(sheetName);}* 1.如果checkedFieldsName没有定义(未⾃定义导出字段),所有字段全部导出 * 2.如果checkedFieldsName进⾏了定义,根据定义字段进⾏导出*/private void initFields(){// 获取对象所有字段对象Field[] fields = clazz.getDeclaredFields();// 过滤出checkedFieldsthis.checkedFields = Arrays.asList(fields).stream().filter(item -> {if(!Objects.isNull(this.checkedFieldsName)) {if (item.isAnnotationPresent(Excel.class)) {return checkedFieldsName.containsKey(item.getName());}} else {return item.isAnnotationPresent(Excel.class);}return false;}).collect(Collectors.toList());// 过滤出fieldsContainDictthis.fieldsContainDict = Arrays.asList(clazz.getDeclaredFields()).stream().filter(item -> !"".equals(item.getAnnotation(Excel.class).dictExp())).collect(Collectors.toList(}/*** 通过扫描字段注解⽣成字典数据*/private void generateObjDict(){if(fieldsContainDict.size() == 0) {return;}if(dicts == null) {dicts = new HashMap<>(); // Map<String, List<Map<String, String>>>}for (Field field : fieldsContainDict) {String dictKey = field.getAnnotation(Excel.class).dictKey();String exps = field.getAnnotation(Excel.class).dictExp();String[] exp = exps.split(",");Map<String, String> keyV = new HashMap<>();dicts.put(dictKey, keyV);for (String s : exp) {String[] out = s.split("=");keyV.put(out[0], out[1]);}System.out.println("字典值:"+ dicts);}}/*** 创建表格样式** @param wb ⼯作薄对象* @return 样式列表*/private Map<String, CellStyle> createStyles(Workbook wb){Map<String, CellStyle> styles = new HashMap<String, CellStyle>();// 数据格式CellStyle style = wb.createCellStyle();style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setBorderRight(BorderStyle.THIN);style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderLeft(BorderStyle.THIN);style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());style.setBorderTop(BorderStyle.THIN);dataFont.setFontHeightInPoints((short) 10);style.setFont(dataFont);styles.put("data", style);// 表头格式style = wb.createCellStyle();style.cloneStyleFrom(styles.get("data"));style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND);Font headerFont = wb.createFont();headerFont.setFontName("Arial");headerFont.setFontHeightInPoints((short) 10);headerFont.setBold(true);headerFont.setColor(IndexedColors.WHITE.getIndex());style.setFont(headerFont);styles.put("header", style);return styles;}/*** ⽣成随机名称,防⽌⽂件复写* @return*/private String generateFileName(){return "D:\\" + UUID.randomUUID().toString().replace("-", "") + ".xlsx";}}12345678910111213141516171819202122232425262728293031323334353637383948 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369使⽤⽅法将对象加上⼯具类需要的注解: @Data@NoArgsConstructor@AllArgsConstructorpublic class Student {@Excel(name = "姓名")private String name;@Excel(name = "年龄")private Integer age;@Excel(name = "出⽣⽇期", dateFormat = "yyyy-MM-dd")private Date birthday;@Excel(name = "性别", dictKey = "sex", dictExp = "1=男,2=⼥")private String sex;}1234567891011121314151617测试字典转换public static void main(String[] args) {ArrayList<Student> data = new ArrayList<>();Student student = new Student();student.setName("tom");student.setAge(19);student.setSex("1");student.setBirthday(new Date());data.add(student);ExcelUtil<Student> util = new ExcelUtil<>(Student.class);util.exportExcel(data, "⼈员信息表");}123456789101112输出结果:结果可以看出, 已将1转换为男了测试选择字段导出:若不⾃定义导出的字段, ⼯具将会把所有带有Excel注解的字段进⾏导出, 如上⽅所⽰。
Java 设置Excel表格数字格式
Java 设置Excel表格数字格式数字字符串用不同格式表示,可代表不同数据意义,如在财务报表里需要用特定的数字字符串格式来反映金额信息、货币币种、数据精确程度、增减趋势等。
本文将通过Java程序介绍在Excel表格中如何来设置数字格式。
工具:Free Spire.XLS for Java(免费版)Jar获取及导入:官网下载Jar包,解压并将lib文件夹下的jar文件导入java程序;或者通过Maven仓库下载导入。
如下导入效果:import com.spire.xls.*;public class NumberFormat {public static void main(String[] args) {//创建工作簿Workbook wb = new Workbook();//获取第一个工作表Worksheet sheet = wb.getWorksheets().get(0);//添加文本到B2、C2,设置文本字体加粗和居中对齐sheet.getCellRange("B2").setText("数字格式");sheet.getCellRange("C2").setText("数字显示结果");sheet.getCellRange("B2:C2").getCellStyle().getExcelFont().isBold(true);sheet.getCellRange("B2:C2").setHorizontalAlignment(HorizontalAlignType.Center);//添加文本到B3sheet.getCellRange("B3").setText("0");//添加数字到C3并设置数字格式sheet.getCellRange("C3").setNumberValue(1234.5678);sheet.getCellRange("C3").setNumberFormat("0");//重复以上步骤,添加文本和数字到其他单元格并设置数字格式sheet.getCellRange("B4").setText("0.00");sheet.getCellRange("C4").setNumberValue(1234.5678);sheet.getCellRange("C4").setNumberFormat("0.00");sheet.getCellRange("B5").setText("#,##0.00");sheet.getCellRange("C5").setNumberValue(1234.5678);sheet.getCellRange("C5").setNumberFormat("#,##0.00");sheet.getCellRange("B6").setText("$#,##0.00");sheet.getCellRange("C6").setNumberValue(1234.5678);sheet.getCellRange("C6").setNumberFormat("$#,##0.00");sheet.getCellRange("B7").setText("0;[Red]-0");sheet.getCellRange("C7").setNumberValue(-1234.5678);sheet.getCellRange("C7").setNumberFormat("0;[Red]-0");sheet.getCellRange("B8").setText("0.00;[Red]-0.00");sheet.getCellRange("C8").setNumberValue(-1234.5678);sheet.getCellRange("C8").setNumberFormat("0.00;[Red]-0.00");sheet.getCellRange("B9").setText("#,##0;[Red]-#,##0");sheet.getCellRange("C9").setNumberValue(-1234.5678);sheet.getCellRange("C9").setNumberFormat("#,##0;[Red]-#,##0");sheet.getCellRange("B10").setText("#,##0.00;[Red]-#,##0.000");sheet.getCellRange("C10").setNumberValue(-1234.5678);sheet.getCellRange("C10").setNumberFormat("#,##0.00;[Red]-#,##0.00");sheet.getCellRange("B11").setText("0.00E+00");sheet.getCellRange("C11").setNumberValue(1234.5678);sheet.getCellRange("C11").setNumberFormat("0.00E+00");sheet.getCellRange("B12").setText("0.00%");sheet.getCellRange("C12").setNumberValue(1234.5678);sheet.getCellRange("C12").setNumberFormat("0.00%");sheet.getCellRange("B13").setText("(###)###-###");sheet.getCellRange("C13").setNumberValue(12345678);sheet.getCellRange("C13").setNumberFormat("(###)###-###");sheet.getCellRange("B14").setText("###-###");sheet.getCellRange("C14").setNumberValue(2020423);sheet.getCellRange("C14").setNumberFormat("###-#-##");//设置2、3列列宽sheet.setColumnWidth(2, 20);sheet.setColumnWidth(3, 20);//保存文档wb.saveToFile("SetNumberFormat.xlsx", ExcelVersion.Version2013);wb.dispose();}}数字格式设置效果:(完)。
java使用EasyExcel导入导出excel
java使⽤EasyExcel导⼊导出excel ⽬录⼀、准备⼯作1、导包⼆、了解注解1、常⽤注解2、@ExcelProperty注解3、@ColumnWith注解4、@ContentFontStyle注解5、@ContentStyle注解6、@HeadFontStyle注解7、ExcelIgnore注解三、编码1、映射实体类----例⼦2、⽣成excel四、结果⼀、准备⼯作1、导包<!-- poi 相关--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><!-- esayexcel 2.1.7 --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.7</version></dependency>⼆、了解注解1、常⽤注解字段注解类注解@ColumnWith(列宽)@ColumnWidth(全局列宽)@ExcelProperty(字段配置)@HeadFontStyle(头样式)@HeadRowHeight(标题⾼度)@ContentFontStyle(内容字体样式)@ContentRowHeight(内容⾼度)2、@ExcelProperty注解必要的⼀个注解,注解中有三个参数value,index分别代表列明,列序号value和index只能⼆选⼀,通常不⽤设置converter1.value 通过标题⽂本对应2.index 通过⽂本⾏号对应@ExcelProperty(value = "编号", index = 0)private Long id;3、@ColumnWith注解设置列宽度,只有⼀个参数value,value的单位是字符长度,最⼤可以设置255个字符,因为⼀个excel单元格最⼤可以写⼊的字符个数就是255个字符public class ImeiEncrypt {@ColumnWidth(value = 255) //excel单个单元格最⼤长度255private String message;}4、@ContentFontStyle注解⽤于设置单元格内容字体格式的注解参数含义fontName字体名称fontHeightInPoints字体⾼度italic是否斜体strikeout是否设置删除⽔平线color字体颜⾊typeOffset偏移量underline下划线bold是否加粗charset编码格式5、@ContentStyle注解设置内容格式注解参数含义dataFormat⽇期格式hidden设置单元格使⽤此样式隐藏locked设置单元格使⽤此样式锁定quotePrefix在单元格前⾯增加`符号,数字或公式将以字符串形式展⽰horizontalAlignment设置是否⽔平居中wrapped设置⽂本是否应换⾏。
Java导出Excel使用POI之SXSSFWorkbook方式
package avicit.mms.mes.mesexceptionbillz.service;
import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.List; import java.util.Map;
import ermodel.HSSFCellStyle; import org.apache.poi.hssf.util.HSSFColor; import ermodel.Cell; import ermodel.CellStyle; import ermodel.Font; import ermodel.Row; import ermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
Java导入导出Excel工具类ExcelUtil
Java导入导出Excel工具类ExcelUtil前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出本项目的持久化层用的是JPA(底层用hibernate实现),所以导入和导出也都是基于实体类的。
在编写ExcelUtil之前,在网上查了一些资料。
java中用来处理Excel的第三方开源项目主要就是POI和JXL。
poi功能强大,但是比较耗资源,对于大数据量的导入导出性能不是太好;jxl功能简单,但是性能比较好。
由于本项目的导入导出更多关注性能问题,而且jxl提供的功能基本也都够用了,于是选择了jxl作为支持。
实战导出就是将List转化为Excel(listToExcel)导入就是将Excel转化为List(excelToList)导入导出中会出现各种各样的问题,比如:数据源为空、有重复行等,我自定义了一个ExcelException异常类,用来处理这些问题。
package common.tool.excel;public class ExcelException extends Exception {public ExcelException() {// TODO Auto-generated constructor stub}public ExcelException(String message) {super(message);// TODO Auto-generated constructor stub}public ExcelException(Throwable cause) {super(cause);// TODO Auto-generated constructor stub}public ExcelException(String message, Throwable cause) { super(message, cause);// TODO Auto-generated constructor stub}}</pre>下面就是该文的主角ExcelUtil登场了,作为一个工具类,其内的所有方法都是静态的,方便使用。
HutoolJava工具类库导出Excel,超级简单!
HutoolJava⼯具类库导出Excel,超级简单!⾸先在POM.xml中加⼊GAV<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.0.7</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.17</version></dependency>Excel写⼊实体类import lombok.AllArgsConstructor;import lombok.Data;import java.util.Date;@Data@AllArgsConstructorpublic class User {private String name;private int age;private Date birthday;}然后在控制层使⽤就⾏@RequestMapping("/export")@ResponseBodypublic void export(HttpServletResponse response) {List<User> list = new ArrayList<>();list.add(new User("zhangsan0", "1231", new Date()));list.add(new User("zhangsan1", "1232", new Date()));list.add(new User("zhangsan2", "1233", new Date()));list.add(new User("zhangsan3", "1234", new Date()));list.add(new User("zhangsan4", "1235", new Date()));list.add(new User("zhangsan5", "1236", new Date()));// 通过⼯具类创建writer,默认创建xls格式ExcelWriter writer = ExcelUtil.getWriter();//⾃定义标题别名writer.addHeaderAlias("name", "姓名");writer.addHeaderAlias("age", "年龄");writer.addHeaderAlias("birthDay", "⽣⽇");// 合并单元格后的标题⾏,使⽤默认标题样式writer.merge(2, "申请⼈员信息");// ⼀次性写出内容,使⽤默认样式,强制输出标题writer.write(list, true);//out为OutputStream,需要写出到的⽬标流//response为HttpServletResponse对象response.setContentType("application/vnd.ms-excel;charset=utf-8");//test.xls是弹出下载对话框的⽂件名,不能为中⽂,中⽂请⾃⾏编码String name = StringUtils.toUtf8String("申请学院");response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");ServletOutputStream out = null;try {out = response.getOutputStream();writer.flush(out, true);} catch (IOException e) {e.printStackTrace();} finally {// 关闭writer,释放内存writer.close();}//此处记得关闭输出Servlet流IoUtil.close(out);}Excel读取1.读取Excel中所有⾏和列,都⽤列表表⽰ExcelReader reader = ExcelUtil.getReader("d:/aaa.xlsx");List<List<Object>> readAll = reader.read();2.读取为Map列表,默认第⼀⾏为标题⾏,Map中的key为标题,value为标题对应的单元格值。
java输出表格
竭诚为您提供优质文档/双击可除java输出表格篇一:java导出报表exceljava导出excel表格20xx-06-0111:03:56作者:zhuangjixiang收藏我要投稿[java]之前做项目的时候需要数据库导出excel格式,由于项目赶没完成,现在分享下如何用java导出excel。
话不多说案例如下:之前做项目的时候需要数据库导出excel格式,由于项目赶没完成,现在分享下如何用java导出excel。
话不多说案例如下:首先要做的是导入一个jxl的包,网上很多。
首先是不连接数据库数据[java]packagejxltest;importjava.io.Fileoutputstream;importjava.io.outputstream;importjava.text.simpledateFormat; importjava.util.arraylist; importjava.util.date; importjava.util.list;importjxl.*;importjxl.format.alignment; importjxl.format.border; importjxl.format.borderlinestyle; importjxl.format.cellFormat; importjxl.write.boolean; bel;importjxl.write.number; importjxl.write.writablecellFormat; importjxl.write.writableFont; importjxl.write.writablesheet; importjxl.write.writableworkbook; publicclassjxlexample{/***数据库导出至excel表格*/publicstaticvoidmain(string[]args){ //准备设置excel工作表的标题string[]title={"编号","产品名称","产品价格","产品数量","生产日期","产地","是否出口"};try{//获得开始时间longstart=system.currenttimemillis();//输出的excel的路径stringfilepath="e:\\testjxl.xls";//创建excel工作薄writableworkbookwwb;//新建立一个jxl文件,即在e盘下生成testjxl.xlsoutputstreamos=newFileoutputstream(filepath);wwb=workbook.createworkbook(os);//添加第一个工作表并设置第一个sheet的名字writablesheetsheet=wwb.createsheet("产品清单",0);labellabel;for(inti=0;i //label(x,y,z)代表单元格的第x+1列,第y+1行,内容z//在label对象的子对象中指明单元格的位置和内容label=newlabel(i,0,title[i]);//将定义好的单元格添加到工作表中sheet.addcell(label);}//下面是填充数据/**保存数字到单元格,需要使用jxl.write.number*必须使用其完整路径,否则会出现错误**///填充产品编号jxl.write.numbernumber=newjxl.write.number(0,1,20xx 1001);sheet.addcell(number);//填充产品名称label=newlabel(1,1,"金鸽瓜子");sheet.addcell(label);/**定义对于显示金额的公共格式*jxl会自动实现四舍五入*例如2.456会被格式化为 2.46,2.454会被格式化为2.45**/jxl.write.numberFormatnf=newjxl.write.numberFormat("#.##");jxl.write.writablecellFormatwcf=newjxl.write.writab lecellFormat(nf);//填充产品价格jxl.write.numbernb=newjxl.write.number(2,1,2.45,wcf);sheet.addcell(nb);//填充产品数量jxl.write.numbernumb=newjxl.write.number(3,1,200);sheet.addcell(numb);/**定义显示日期的公共格式*如:yyyy-mm-ddhh:mm**/simpledateFormatsdf=newsimpledateFormat("yyyy-mm-dd ");stringnewdate=sdf.format(newdate());//填充出产日期label=newlabel(4,1,newdate);sheet.addcell(label);//填充产地label=newlabel(5,1,"陕西西安");sheet.addcell(label);/**显示布尔值**/jxl.write.booleanbool=newjxl.write.boolean(6,1,true);sheet.addcell(bool);/**合并单元格*通过writablesheet.mergecells(intx,inty,intm,intn);来实现的*表示将从第x+1列,y+1行到m+1列,n+1行合并***/sheet.mergecells(0,3,2,3);label=newlabel(0,3,"合并了三个单元格");packagejxltest;importjava.io.Fileoutputstream;importjava.io.outputstream; importjava.text.simpledateFormat; importjava.util.arraylist; importjava.util.date; importjava.util.list;importjxl.*;importjxl.format.alignment; importjxl.format.border; importjxl.format.borderlinestyle; importjxl.format.cellFormat; importjxl.write.boolean; bel;importjxl.write.number; importjxl.write.writablecellFormat; importjxl.write.writableFont; importjxl.write.writablesheet; importjxl.write.writableworkbook; publicclassjxlexample{/***数据库导出至excel表格*/publicstaticvoidmain(string[]args){//准备设置excel工作表的标题string[]title={"编号","产品名称","产品价格","产品数量","生产日期","产地","是否出口"};try{//获得开始时间longstart=system.currenttimemillis();//输出的excel的路径stringfilepath="e:\\testjxl.xls";//创建excel工作薄writableworkbookwwb;//新建立一个jxl文件,即在e盘下生成testjxl.xlsoutputstreamos=newFileoutputstream(filepath);wwb=workbook.createworkbook(os);//添加第一个工作表并设置第一个sheet的名字writablesheetsheet=wwb.createsheet("产品清单",0);labellabel;for(inti=0;i //label(x,y,z)代表单元格的第x+1列,第y+1行,内容z//在label对象的子对象中指明单元格的位置和内容label=newlabel(i,0,title[i]);//将定义好的单元格添加到工作表中sheet.addcell(label);}//下面是填充数据/**保存数字到单元格,需要使用jxl.write.number*必须使用其完整路径,否则会出现错误**///填充产品编号jxl.write.numbernumber=newjxl.write.number(0,1,20xx 1001);sheet.addcell(number);//填充产品名称label=newlabel(1,1,"金鸽瓜子");sheet.addcell(label);/**定义对于显示金额的公共格式*jxl会自动实现四舍五入*例如2.456会被格式化为 2.46,2.454会被格式化为2.45**/jxl.write.numberFormatnf=newjxl.write.numberFormat("#.##");jxl.write.writablecellFormatwcf=newjxl.write.writab lecellFormat(nf);//填充产品价格jxl.write.numbernb=newjxl.write.number(2,1,2.45,wcf);sheet.addcell(nb);//填充产品数量jxl.write.numbernumb=newjxl.write.number(3,1,200);sheet.addcell(numb);/**定义显示日期的公共格式*如:yyyy-mm-ddhh:mm**/simpledateFormatsdf=newsimpledateFormat("yyyy-mm-dd ");stringnewdate=sdf.format(newdate());//填充出产日期label=newlabel(4,1,newdate);sheet.addcell(label);//填充产地label=newlabel(5,1,"陕西西安");sheet.addcell(label);/**显示布尔值**/jxl.write.booleanbool=newjxl.write.boolean(6,1,true);sheet.addcell(bool);/**合并单元格*通过writablesheet.mergecells(intx,inty,intm,intn);来实现的*表示将从第x+1列,y+1行到m+1列,n+1行合并***/sheet.mergecells(0,3,2,3);label=newlabel(0,3,"合并了三个单元格");[java]viewplaincopyprintsheet.addcell(label);***定义公共字体格式*通过获取一个字体的样式来作为模板篇二:java实现生成pdF(包含文字,表格,图片) 需要的lib:itext-2.1.7.jaritextasian.jarpackagecom.demo.test;importjava.awt.color;importjava.io.File;importjava.io.Fileoutputstream;importcom.lowagie.text.chunk;importcom.lowagie.text.document;importcom.lowagie.text.Font;importcom.lowagie.text.chapter;importcom.lowagie.text.element;importcom.lowagie.text.image;importcom.lowagie.text.pagesize;importcom.lowagie.text.paragraph;importcom.lowagie.text.phrase;importcom.lowagie.text.pdf.baseFont;importcom.lowagie.text.pdf.pdfpcell;importcom.lowagie.text.pdf.pdfptable;importcom.lowagie.text.pdf.pdfwriter;/***生成pdF文件**@authorsmile*qq:1963938311**/publicclasspdFdemo{privatecolorblack=newcolor(0,0,0);//黑色privatecolorred=newcolor(255,0,0);//红色privatecolorblue=newcolor(0,0,255);//蓝色privateintbold=Font.bold;//粗体privateintnormal=Font.noRmal;//正常字体privateintitalic=Font.italic;//斜体privateintbolditalic=Font.bolditalic;//粗斜体privatefloatsetting=100;//首行缩进参数publicdocumentcreatedoc(stringfilename)throwsexception{。
java通用的导出excel合并单元格格式(二)
java通⽤的导出excel合并单元格格式(⼆)表格效果图思路:1 excel 标题头这⾥的标题写成了固定标题的第⼀列需要合并的单元格需要填充String[] head0 = new String[] { "登录名", "是否使⽤", "单位名称", "机要员", "联系⽅式", "管辖区局","级别", "作业⼈员情况", "作业⼈员情况", "作业⼈员情况", "作业⼈员情况", "作业⼈员情况","系统数据总数", "维保电梯(台)","设备数","设备数","分配情况(台)","分配情况(台)","单位地址" }; //在excel中的第2⾏每列的参数标题的第⼆列/* 在excel中的第3⾏每列(合并列)的参数这⾥需要注意的是从第⼏列合并的时候需要把前⾯不需要合并⾏的列⽤"" 补上(下表是从第7列开始合并的⾏的所以前⾯补了 6个"", 中间兼职和总数之间有⼀列是不需要合并⾏的也补了⼀个"") */String[] head1 = new String[] { " ", " ", " ", " ", " ", " ","总数", "确定", "库内", "库外", "兼职", "","总数", "认保", "认脱","分配", "未分配"};2 excel 内容通⽤⽅法写⼊从后台数据库查询到的数据到 excel后台业务逻辑(控制器从后台数据库查询数据)@RequestMapping(value = "exportMntOrgData")public void exportMntOrgData(HttpServletRequest request, HttpServletResponse response){Map<String, Object> map = new HashMap<String, Object>();Principal principal = UserUtils.getPrincipal();getManagerOrgId(map); // 判断当前登录账号是否是市局的id 如果是 supOrgId置为空查询所有// 2、导出String filename = "管理区局("+principal.getOrgname()+") 维保单位列表 .xls";List<Map<String, Object>> list = (List<Map<String, Object>>) mntOrgListStatisticsService.exportMntOrgList(map);//String path="exportTitle/mntWorker.xml";String[] head0 = new String[] { "登录名", "是否使⽤", "单位名称", "机要员", "联系⽅式", "管辖区局","级别", "作业⼈员情况", "作业⼈员情况", "作业⼈员情况", "作业⼈员情况", "作业⼈员情况","系统数据", "设备数","设备数","设备数","分配情况(台)","分配情况(台)","单位地址" };//在excel中的第2⾏每列的参数/* 在excel中的第3⾏每列(合并列)的参数这⾥需要注意的是从第⼏列合并的时候需要把前⾯不需要合并⾏的列⽤"" 补上(下表是从第7列开始合并的⾏的所以前⾯补了 6个"", 中间兼职和总数之间有⼀列是不需要合并⾏的也补了⼀个"") */String[] head1 = new String[] { "", "", "", "", "", "","总数", "确定", "库内", "库外", "兼职", "","总数", "认保", "认脱","分配", "未分配"};String[] headnum0 = new String[] { "1,2,0,0", "1,2,1,1","1,2,2,2","1,2,3,3", "1,2,4,4","1,2,5,5","1,2,6,6","1,1,7,11" , "1,2,12,12", "1,1,13,15", "1,1,16,17","1,2,18,18"};//对应excel中的⾏和列,下表从0开始{"开始⾏,结束⾏,开始列,结束列"}String[] headnum1 = new String[] { "2,2,7,7", "2,2,8,8", "2,2,9,9","2,2,10,10","2,2,11,11","2,2,13,13","2,2,14,14","2,2,15,15","2,2,16,16","2,2,17,17"};String[] colName = new String[] { "username","username","mntOrgName", "name", "mobile", "manageOrgName", "grade" ,"userTotal","userTotal" , "userTotal1", "userTotal2", "userTotal3","equTotal" , "equTotal", "mntEquCount", "notMntEquCount","assignedEquCount" , "norAssignedEquCount", "address"};//需要显⽰在excel中的参数对应的值,因为是⽤map存的,放的都是对应的key try {ExcelUtil.reportMergeXls(request, response, list, filename, head0,headnum0, head1, headnum1, colName);//utils类需要⽤到的参数} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}从后台查询 List<Map<String, Object>> 得到2条的json 格式数据如下:[ {username=邓润军,username=440225************,mntOrgName=........},{username=邓润军,username=440225************,mntOrgName=........}]通⽤的⽅法写在 ExcelUtil⾥⾯package com.nskj.utils;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Scanner;import java.util.Map.Entry;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import ermodel.HSSFCell;import ermodel.HSSFCellStyle;import ermodel.HSSFFont;import ermodel.HSSFRow;import ermodel.HSSFSheet;import ermodel.HSSFWorkbook;import org.apache.poi.ss.util.CellRangeAddress;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**** excel 导出⼯具类* @author Administrator**/public class ExcelUtil {private static DecimalFormat df = new DecimalFormat("0");// 默认单元格格式化⽇期字符串private static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");// 格式化数字private static DecimalFormat nf = new DecimalFormat("0.00");private final static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);/**** 读取本地⽂件txt 获取excel标题* @param path* @return*/public static String getTitle(String path){FileInputStream fis = null;InputStreamReader isr = null;BufferedReader br = null; //⽤于包装InputStreamReader,提⾼处理性能。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//创建单元格格式:设置水平对齐为向左对齐
jxl.write.WritableCellFormat LwcfF = new jxl.write.WritableCellFormat(wf);
LwcfF.setAlignment(jxl.write.Alignment.LEFT);
wsheet.addCell(new Label(2,2, "测试test", CMwcfF));
//在坐标为(3,3)的单元格addCell(new Number(23, 14, 2.00, CBwcfF));
//写入
wbook.write();
jxl.write.WritableCellFormat CMwcfF = new jxl.write.WritableCellFormat(wf);
CMwcfF.setAlignment(jxl.write.Alignment.LEFT);
//设置垂直对齐为向上对齐
CMwcfF.setVerticalAlignment(VerticalAlignment.TOP);
//模板工作簿对象
Workbook tBook = Workbook.getWorkbook(tFile);
//输出工作簿对象
WritableWorkbook wbook = Workbook.createWorkbook(os, tBook);
//在坐标为(0,0)的单元格写入"测试"字符串使用8号红色小字体,向右对齐
wsheet.addCell(new Label(0, 0, "test", RwcfF));
//在坐标为(1,1)的单元格写入"test"字符串使用8号红色小字体,向左对齐
wsheet.addCell(new Label(1, 1, "test", LwcfF));
//在坐标为(2,2)的单元格写入"测试test"字符串使用8号红色小字体,居中对齐
{
public static void main(String [] args)
{
String templatePath = "c:\\template.xls";//模板文件名
String outFileStr = "c:\\test.xls";//测试文件名(输出文件)
try
{
//创建小字体:Arial,大小为8号,非粗体,非斜体
//创建单元格格式:设置水平对齐为居中对齐
jxl.write.WritableCellFormat CwcfF = new jxl.write.WritableCellFormat(wf);
CwcfF.setAlignment(jxl.write.Alignment.CENTRE);
jxl.write.WritableCellFormat CBwcfF = new jxl.write.WritableCellFormat(Bwf);
wbook.close();
tBook.close();
//关闭文件输出流
os.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
jxltest.java
import java.io.File;
import java.io.FileOutputStream;
import jxl.Workbook;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
WritableFont wf = new WritableFont(WritableFont.ARIAL, 8,WritableFont.NO_BOLD, false);
//字体颜色为红色
wf.setColour(jxl.format.Colour.RED);
//创建大字体:Arial,大小为18号,粗体,非斜体
import bel;
import jxl.write.Number;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class jxltest
//设置右边框线为实线
CBwcfF.setBorder(jxl.format.Border.RIGHT, BorderLineStyle.MEDIUM);
//设置顶部框线为实线
CBwcfF.setBorder(jxl.format.Border.BOTTOM, BorderLineStyle.MEDIUM);
CBwcfF.setAlignment(jxl.write.Alignment.CENTRE);
//设置垂直对齐为居中对齐
CBwcfF.setVerticalAlignment(VerticalAlignment.CENTRE);
//设置顶部边框线为实线(默认是黑色--也可以设置其他颜色)
CBwcfF.setBorder(jxl.format.Border.TOP, BorderLineStyle.MEDIUM);
CMwcfF.setWrap(true);
File tFile = new File(templatePath);//创建模板文件对象
File outFile = new File(outFileStr);//创建输出文件对象
//创建文件输出流对象
FileOutputStream os = new FileOutputStream(outFile);
WritableFont Bwf = new WritableFont(WritableFont.ARIAL, 18,WritableFont.NO_BOLD, false);
Bwf.setColour(jxl.format.Colour.RED);
//创建单元格格式:设置水平对齐为向右对齐
jxl.write.WritableCellFormat RwcfF = new jxl.write.WritableCellFormat(wf);