java集成poi框架

介绍 : Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

下面简单介绍一下如何使用该框架:

一:导入依赖

 <!--        excel解析依赖--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>${org.poi-version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>${org.poi-version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-examples</artifactId><version>${org.poi-version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-excelant</artifactId><version>${org.poi-version}</version></dependency><!-- https://mvnrepository.com/artifact/com.monitorjbl/xlsx-streamer --><dependency><groupId>com.monitorjbl</groupId><artifactId>xlsx-streamer</artifactId><version>2.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><!--阿里巴巴EasyExcel依赖--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><!--        <dependency>--><!--            <groupId>org.projectlombok</groupId>--><!--            <artifactId>lombok</artifactId>--><!--        </dependency>--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.hynnet</groupId><artifactId>jxl</artifactId><version>2.6.12.1</version></dependency><!-- https://mvnrepository.com/artifact/com.bulucat/BeautyEye --><dependency><groupId>com.bulucat</groupId><artifactId>BeautyEye</artifactId><version>1.0.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.21</version></dependency><dependency><groupId>javax.annotation</groupId><artifactId>javax.annotation-api</artifactId><version>1.3.2</version></dependency>

二:创建实体类及dao层(查询得到结果集封装在list中即可,此处不做过多赘述)

三:在serviceImpl中处理结果集

 @AutowiredDbToExcelDao dbToExcelDao;@Overridepublic List<String[]> getAllCity(QueryDto dto) {List<CityInfo> cityInfoList = dbToExcelDao.getAllCity(dto);List<String[]> result=new ArrayList<>();for (CityInfo cityInfo : cityInfoList) {String[] cityInfoArr = new String[7];//将查询到的结果集转换成字符串存入字符串数组中cityInfoArr[0] = xxx;cityInfoArr[1] = xxx;cityInfoArr[2] = xxx;cityInfoArr[3] = xxx;cityInfoArr[4] = xxx;//将该字符串数组存入list中result.add(cityInfoArr);}return result;}

四:在controller中调用service对象使用poi工具类导出表格。

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;/***** 文件导入导出工具类***/
public class ExcelUtils {/*** 导出excel文件的方法** @param titles 输出到excel的表头* @param datas  数据库的表中的数据 集合对象* @param out excel(File) 输出到指定的路径 (OutPutStream)*/public static void export(List<String[]> titles, List<List<String[]>> datas, OutputStream out) {// 创建工作表HSSFWorkbook work = new HSSFWorkbook();for (int k = 0;k<datas.size();k++){String sheetname = "";// 创建sheet表if(k == 0){if(datas.size() > 1){sheetname = "xxx";//sheet名}else {sheetname = "xxx";//sheet名}}else if(k == 1){sheetname = "xxx";//sheet名}else if(k == 2){sheetname = "xxx";//sheet名}HSSFSheet sheet = work.createSheet(sheetname);// 创建表头【表头数据来源】Row headRow = sheet.createRow(0);// 循环输出标题for (int i = 0; i < titles.get(k).length; i++) {// 设置字体HSSFCellStyle redStyle = work.createCellStyle();
//           CellStyle redStyle = work.createCellStyle();HSSFFont redFont = work.createFont();//字体颜色redFont.setColor((short) 9);//设置字体大小redFont.setFontHeightInPoints((short) 10);//字体样式redFont.setFontName("Microsoft YaHei");//加粗redFont.setBold(true);redStyle.setFont(redFont);//设置居中redStyle.setAlignment(HorizontalAlignment.CENTER);redStyle.setVerticalAlignment(VerticalAlignment.CENTER);//背景色redStyle.setFillForegroundColor(IndexedColors.BLACK.getIndex());redStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 上薄边框redStyle.setBorderTop(BorderStyle.THIN);// 下薄边框redStyle.setBorderBottom(BorderStyle.THIN);// 左薄边框redStyle.setBorderLeft(BorderStyle.THIN);// 右薄边框redStyle.setBorderRight(BorderStyle.THIN);// 下边框:黑色redStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 右边框:黑色redStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 左边框:黑色redStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 上边框:黑色redStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());//创建cell,嵌入样式Cell cell = headRow.createCell(i);cell.setCellStyle(redStyle);cell.setCellValue(titles.get(k)[i]); // 设置cell中的内容}// 表体内容// 设置表体内容 嵌套循环for (int row = 0; row < datas.get(k).size(); row++) {// 创建行HSSFRow sheetRow = sheet.createRow(row + 1);// 循环 创建列for (int c = 0; c < datas.get(k).get(row).length; c++) {sheet.autoSizeColumn(c, true);// 设置字体HSSFCellStyle redStyle = work.createCellStyle();
//           CellStyle redStyle = work.createCellStyle();HSSFFont redFont = work.createFont();//字体颜色redFont.setColor((short) 8);//设置字体大小redFont.setFontHeightInPoints((short) 10);//字体样式redFont.setFontName("等线");//加粗
//                redFont.setBold(true);redStyle.setFont(redFont);//设置居中redStyle.setAlignment(HorizontalAlignment.CENTER);redStyle.setVerticalAlignment(VerticalAlignment.CENTER);//背景色
//                redStyle.setFillForegroundColor(IndexedColors.BLACK.getIndex());
//                redStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 上薄边框redStyle.setBorderTop(BorderStyle.THIN);// 下薄边框
//                    if(row == datas.size()){redStyle.setBorderBottom(BorderStyle.THIN);
//                    }// 左薄边框redStyle.setBorderLeft(BorderStyle.THIN);// 右薄边框
//                    if(c == datas.get(k).get(row).length-1){redStyle.setBorderRight(BorderStyle.THIN);
//                    }// 下边框:黑色redStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 右边框:黑色redStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 左边框:黑色redStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 上边框:黑色redStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());HSSFCell sheetCell = sheetRow.createCell(c);sheetCell.setCellStyle(redStyle);// 设置内容sheetCell.setCellValue(datas.get(k).get(row)[c]);}}}// 创建完成后,内存创建的Excel输出到文件中try {work.write(out);out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}/***  导入excel文件的方法**  suffix: 传入excel的后缀名*      excel  2003版的后缀为(xls) HSSFWorkbook  2007版的后缀为(xlsx)XSSFWorkbook*  fis :   通过输入流来读取excel的内容*  startRow: 读取内容的起始行**  @return 返回导入的数据    List<String[]>**/public static List<String[]> importData(MultipartFile file, int startrow) {List<String[]> datas = new ArrayList<String[]>();// 创建表格对象Workbook work = null;try {//获取文件流对象InputStream fis = file.getInputStream();//获取文件的后缀String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 判断后缀名if (suffix.equals(".xls")) {work = new HSSFWorkbook(fis); // 2003的工作表对象} else if (suffix.equals(".xlsx")) { //work = new XSSFWorkbook(fis); // 2007的工作表对象} else {return null;}} catch (IOException e) {e.printStackTrace();}// 获取sheet表格Sheet sheet = work.getSheetAt(0);if (sheet == null) { // 代表一个sheet表格也没有return null;}// 获取一共多少行int rownum = sheet.getLastRowNum();if (rownum == 0 || rownum+1 == startrow) {return null;}for (int i = startrow; i <= rownum; i++) {// 获取行Row row = sheet.getRow(i);// 获取列short first = row.getFirstCellNum(); //起始列的下标short num = row.getLastCellNum();    //终止列的下标String[] cols = new String[num];    //存放当前行所有的列内容for (int j = first; j < num; j++) {// 处理列对象Cell cell = row.getCell(j);
//                if(j == 10){
//                    String[] dates = row.getCell(7).toString().split("-");
//                    String year = dates[2];
//                    String  month = dates[1].substring(0,dates[1].length()-1);
//                    //获取年份差
//                    int yx = Integer.parseInt(row.getCell(1).toString().substring(0,4) )- Integer.parseInt(year);
//                    //获取月份差
//                    int mx = Integer.parseInt(row.getCell(1).toString().substring(4,6)) - Integer.parseInt(month);
//                    cols[j] = yx*12+mx+1 + "";
//                    continue;
//                }//获取指定列的内容, 都转换为String类型cols[j] = parseCell(cell);}datas.add(cols);  //列处理完成以后,把该行所有列添加集合中}return datas;}// 转换类型private static String parseCell(Cell cell) {String cellValue = "";if(cell == null){return null;}//判断如果是String类型 则去除空格if (cell.getCellTypeEnum() == CellType.STRING) {cellValue = cell.getStringCellValue().trim();} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) { //如果是boolean类型则获取boolean类型的值cellValue = String.valueOf(cell.getBooleanCellValue());} else if (cell.getCellTypeEnum() == CellType.NUMERIC) { //如果是数字类型, 则判断是日期类型还是普通数字if (HSSFDateUtil.isCellDateFormatted(cell)) { // 判断日期类型double d = cell.getNumericCellValue();Date date = HSSFDateUtil.getJavaDate(d);cellValue = new SimpleDateFormat("yyyy-MM-dd").format(date);} else { // 否cellValue = new DecimalFormat("#.######").format(cell.getNumericCellValue());}} else {cellValue = "";}return cellValue;}//图片处理public static List<String> savePic(InputStream fis) throws Exception {HSSFWorkbook workbook = (HSSFWorkbook) WorkbookFactory.create(fis);List<HSSFPictureData> pictures = workbook.getAllPictures();HSSFSheet sheet = workbook.getSheetAt(0);List<String> picList = new ArrayList<>();for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();if (shape instanceof HSSFPicture) {HSSFPicture pic = (HSSFPicture) shape;int row = anchor.getRow1();int pictureIndex = pic.getPictureIndex() - 1;HSSFPictureData picData = pictures.get(pictureIndex);//获取文件后缀String ext = picData.suggestFileExtension();//获取图片内容byte[] data = picData.getData();//通过文件流将图片写入到指定的位置String filename = UUID.randomUUID().toString().replace("-", "");FileOutputStream out = new FileOutputStream("D:\\upload\\"+ filename +"."+ext);out.write(data);out.close();picList.add(filename+"."+ext);}}return picList;}
}
    @AutowiredDbToExcelService dbToExcelService;//导出结果表@RequestMapping("export")public void exportFileReconnect(HttpServletResponse res,QueryDto querydto) throws IOException {//定义添加标题String[] title1={"xx","xx","xx","xx","xx"};List<String[]> title = new ArrayList<>();title.add(title1);//定义添加内容,也可以存入多个list,作一个表中的不同sheetList<String[]> list1 = dbToExcelService.getAllReconnect(querydto);List<List<String[]>> list = new LinkedList<>();list.add(list1);//设置响应头,告知浏览器是下载操作res.setHeader("Content-Disposition","attachment;filename=futongtongji.xls");//设置MIME类型res.setContentType("application/vnd.ms-excel");//这里要传递的字节流数据,excel为字节流文件ExcelUtils.export(title,list,res.getOutputStream());}@AutowiredExcelToDbService excelToDbService;//文件导入数据库@RequestMapping("import")@ResponseBodypublic ResultData importFile(MultipartFile file) throws Exception {//获取excel的数据List<String[]> list = ExcelUtils.importData(file, 1);//获取excel中图片的数据List<String> strings = ExcelUtils.savePic(file.getInputStream());for (int i = 0; i < list.size(); i++) {//将图片数据渲染到excel表格中list.get(i)[1]= strings.get(i);}//上传数据就是一个增加的过程ResultData resultData = excelToDbService.insertAll(list);return resultData;}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/167081.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

17 redis集群方案

1、RedisCluster分布式集群解决方案 为了解决单机内存&#xff0c;并发等瓶颈&#xff0c;可使用此方案解决问题. Redis-cluster是一种服务器Sharding技术&#xff0c;Redis3.0以后版本正式提供支持。 这里的集群是指多主多从&#xff0c;不是一主多从。 2、redis集群的目标…

pair和typedef

文章目录 一、pair用法1.2、pair的创建和初始化1.3、pair对象的操作1.4、(make_pair)生成新的pair对象1.5、通过tie获取pair元素值 2、typedef2.1、什么是typedef2.2、typedef用法2.2.1、对于数据类型使用例如&#xff1a;2.2.2、对于指针的使用例如2.2.3、对于结构体的使用 2.…

java springboot测试类虚拟MVC环境 匹配返回值与预期内容是否相同 (JSON数据格式) 版

上文java springboot测试类鉴定虚拟MVC请求 返回内容与预期值是否相同我们讲了测试类中 虚拟MVC发送请求 匹配返回内容是否与预期值相同 但是 让我意外的是 既然没人骂我 因为我们实际开发 返回的基本都是json数据 字符串的接口场景是少数的 我们在java文件目录下创建一个 dom…

2023年10月纸巾市场分析(京东天猫淘宝平台纸巾品类数据采集)

双十一大促期间&#xff0c;刚需品的纸巾是必囤商品之一。今年双十一&#xff0c;京东数据显示&#xff0c;10月23日至29日&#xff0c;清洁纸品成交额同比增长40%&#xff0c;由此也拉动了10月纸巾市场的销售。 鲸参谋数据显示&#xff0c;今年10月&#xff0c;京东平台纸巾市…

【日常总结】如何禁止浏览器 http自动跳转成https

一、场景 二、问题 三、解决方案 3.1 chrome 浏览器 3.2 edge 浏览器&#xff1a; 3.3 Safari 浏览器 3.4 Firefox 浏览器 3.5 Microsoft Edge 一、场景 公司网站 http:// 谷歌浏览器中自动转换成 https:// 导致无法访问 二、问题 nginx配置ssl 443接口&#xff0c; ht…

SOLIDWORKS 2024新功能之Electrical篇

SOLIDWORKS 2024 Electrical篇目录概览 • 对齐零部件 • 更改多个导轨和线槽的长度 • 过滤辅助和附件零件 • 2D 机柜中的自动零件序号 • 移除制造商零件数据 • 重置未定义的宏变量 • 使用范围缩短列表 • SOLIDWORKS Electrical Schematic 增强功能 1、对齐零部件…

ONNX实践系列-修改yolov5-seg的proto分支输出shape

一、目标 本文主要介绍要将原始yolov5分割的输出掩膜从[b,c,h,.w]修改为[b, h, w, c] 原来的: 目标的: 代码如下: Descripttion: version: @Company: WT-XM Author: yang jinyi Date: 2023-09-08 11:26:28 LastEditors: yang jinyi LastEditTime: 2023-09-08 11:48:01 …

Threejs_14 制作圣诞贺卡

继续跟着老陈打码学习&#xff01;&#xff01;&#xff01;支持&#xff01;&#xff01;&#xff01; 效果图 链接&#xff1a;https://pan.baidu.com/s/1Ft8U2HTeqmpyAeesL31iUg 提取码&#xff1a;6666 使用到的 模型文件和资源等都为老陈打码提供&#xff01;&#x…

【腾讯云云上实验室】探索保护数据之盾背后的安全监控机制

当今数字化时代&#xff0c;数据安全成为了企业和个人最为关注的重要议题之一。随着数据规模的不断增长和数据应用的广泛普及&#xff0c;如何保护数据的安全性和隐私性成为了迫切的需求。 今天&#xff0c;我将带领大家一起探索腾讯云云上实验室所推出的向量数据库&#xff0c…

新版PY系列离线烧录器,支持PY002A/002B/003/030/071等MCU各封装,不同 FLASH 大小型号

PY系列离线烧录器&#xff0c;目前支持PY32F002A/002B/002/003/030/071/072/040/403/303 各封装、不同 FLASH 大小型号。PY离线烧录器需要搭配上位机软件使用&#xff0c;上位机软件可以在芯岭技术官网上下载&#xff0c;还包括了离线烧录器的使用说明。PY离线烧录器使用MINI U…

金融机构如何高效率考勤?这个技巧帮了大忙!

在现代社会&#xff0c;随着科技的不断发展&#xff0c;人脸识别技术作为一种高效、便捷的身份验证手段&#xff0c;逐渐应用于各个领域&#xff0c;其中之一便是人脸考勤系统。 传统的考勤方式存在一系列问题&#xff0c;如卡片打卡容易被冒用、签到表容易造假等&#xff0c;而…

CTFUB-web前置技能-HTTP协议

burp抓包,抓第二次的 修改请求方式为CTFHUB

算法笔记:OPTICS 聚类

1 基本介绍 OPTICS(Ordering points to identify the clustering structure)是一基于密度的聚类算法 OPTICS算法是DBSCAN的改进版本 在DBCSAN算法中需要输入两个参数&#xff1a; ϵ 和 MinPts &#xff0c;选择不同的参数会导致最终聚类的结果千差万别&#xff0c;因此DBCSAN…

线上PDF文件展示

场景&#xff1a; 请求到的PDF&#xff08;url链接&#xff09;&#xff0c;将其展示在页面上 插件&#xff1a; pdfobject &#xff08;我使用的版本&#xff1a; "pdfobject": "^2.2.12" &#xff09; 下载插件就不多说了&#xff0c;下面将其引入&a…

【Clang Static Analyzer 代码静态检测工具详细使用教程】

Clang Static Analyzer sudo apt-get install clang-tools scan-build cmake .. scan-build make -j4 编译完成之后会在终端提示在哪里查看报错文档: scan-build: 55 bugs found. scan-build: Run scan-view /tmp/scan-build-2023-11-24-150637-6472-1 to examine bug report…

Liunx Ubuntu Server 安装配置 Docker

1. 安装Docker 1.1 更新软件包列表 sudo apt update1.2 添加Docker存储库 sudo apt install apt-transport-https ca-certificates curl gnupg-agent software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-a…

Django QuerySet.order_by SQL注入漏洞(CVE-2021-35042)

漏洞描述 Django 于 2021年7月1日发布了一个安全更新&#xff0c;修复了函数QuerySet.order_by中的 SQL 注入漏洞。 参考链接&#xff1a; Django security releases issued: 3.2.5 and 3.1.13 | Weblog | Django 该漏洞需要开发人员使用order_by功能。此外&#xff0c;还可…

加入华为云鲲鹏极简开发创造营,激活创造力,探索无限可能!

数字经济时代&#xff0c;速度、效率、质量安全已成为各行业告诉拓新发展的关键&#xff0c;华为云不断打磨敏捷安全开发的软件平台&#xff0c;为更高效率的生产力变革积蓄能量。 在刚刚过去不久的2023华为全联接大会上&#xff0c;华为最新发布了华为云CodeArts与鲲鹏DevKit…

关于配置文件中秘钥信息加密实现方案的一些思考

关于配置文件中秘钥信息加密实现方案的一些思考 背景实现方案 背景 配置信息文件中(代码中), 不应该有明文的秘钥信息. 需要找一种方案去做加密处理. 实现方案 我们可以在项目指定目录上传一份加密/解密程序, 例如: jasypt-gui.jar. 启动时: 配置JVM参数, 对加密的信息进行解…

2023 Unite 大会关于“Muse“ AI 大模型训练

Unity Muse 借助强大的 AI 能力帮助你探索、构思和迭代&#xff0c;其中包括纹理和精灵两项功能&#xff0c;可将自然语言和视觉输入转化为可用资产。 将 AI 引入 Unity Editor 中的 Muse 提供了更快将想法转化为实物的选项。您可以调整并使用文本提示、图案、颜色和草图&…