java生成excel,uniapp微信小程序接收excel并打开

java引包,引的是apache.poi

java 复制代码
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>

写一个测试类,把excel输出到指定路径

java 复制代码
    public static void main(String[] args) {
        // 学生类
        @Data
        @AllArgsConstructor
        class Student implements Serializable {
            private static final long serialVersionUID = 1L;
            private String name;
            private Integer age;
            private String sex;
        }
        // 将要导出的数据
        List<Student> list = new ArrayList<>();
        list.add(new Student("张潇", 23, "男"));
        list.add(new Student("李小思", 19, "女"));
        list.add(new Student("某人", 66, "未知"));
        try (
            // 创建一个Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            // 输出流, 保存到指定路径, 请确保路径存在
            FileOutputStream fileOutputStream = new FileOutputStream("D:/A_software/templast/student.xlsx");
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        ) {
            // 创建一个工作表sheet
            Sheet sheet = workbook.createSheet("Sheet1");
            // 设置表头
            List<String> sheetHeadList = Arrays.asList("姓名", "年龄", "性别");
            Row sheetHead = sheet.createRow(0);
            for (int index = 0; index < sheetHeadList.size(); index++) {
                // 设置每列宽度 大小乘以256,调整13即可
                sheet.setColumnWidth(index, 13 * 256);
                sheetHead.createCell(index).setCellValue(sheetHeadList.get(index));
            }
            // 设置值
            for (int index = 0; index < list.size(); index++) {
                // 创建行,表头是第一行,所以这里 + 1
                Row row = sheet.createRow(index + 1);
                Student student = list.get(index);
                // 行里创建单元格并设置值
                row.createCell(0).setCellValue(student.getName());
                row.createCell(1).setCellValue(student.getAge());
                row.createCell(2).setCellValue(student.getSex());
            }
            workbook.write(bufferedOutputStream);
        } catch (IOException e) {
            throw new RuntimeException("导出excel失败");
        }
    }

执行之后,去打开excel

没毛病,接下来是把excel传给前端,小程序打开,有很多种方式:

  1. 后端保存excel到指定位置,返回文件下载的url给前端,前端根据url下载。
  2. 后端保存excel后,返回文件流,前端调用接口生成excel时,接收返回的文件流即可。
  3. 后端不保存excel,把excel输出成字节数组,再转成base64格式,返回前端base64字符串。

我这里用了第三种,因为我是导出excel给用户,后端不需要存下这个文件。

上面的测试方法改一下就行了

java 复制代码
// 输出流, 保存到指定路径, 请确保路径存在
FileOutputStream fileOutputStream = new FileOutputStream("D:/A_software/templast/student.xlsx");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

把上面的输出流换成

java 复制代码
ByteArrayOutputStream bufferedOutputStream = new ByteArrayOutputStream();

然后调用workbook.write写入

java 复制代码
workbook.write(bufferedOutputStream);
// 写入完了之后,转成字节数组
byte[] bytes = bufferedOutputStream.toByteArray();
// 再转成base64格式
String base64 = Base64.encodeBase64String(bytes);

最后直接返回base64字符串给前端就行了。


前端微信小程序

javascript 复制代码
// 假设接口请求完成,返回了base64字符串
const base64Value = 接口返回
// 文件保存路径
const filePath = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.xlsx`
// 保存excle到手机上
wx.getFileSystemManager().writeFile({
	filePath: filePath,
	data: base64Value ,
	encoding: 'base64',
	success: () => {
        // 保存成功后打开,也可以不打开,看你需求
		setTimeout(() => {
			uni.openDocument({
				filePath: filePath,
				showMenu: true,
				fileType: 'xlsx',
				fail: (error) => {
					// 打开excel失败
				}
			})
		}, 500)
	},
	fail: (error) => {
		// 保存excel失败
	}
})

完事了,如果是复杂样式的excel,推荐后端引包【freemarker】包生成excel,支持自定义,就是代码有点繁琐,具体看看我的java导出word文档文章,思路基本一致。


码字不易,于你有利,勿忘点赞

相关推荐
计算机学姐12 分钟前
基于SpringBoot的小型民营加油站管理系统
java·vue.js·spring boot·后端·mysql·spring·tomcat
小雅痞17 分钟前
[Java][Leetcode middle] 151. 反转字符串中的单词
java·leetcode
ThomasChan12319 分钟前
Win10 安装单机版ES(elasticsearch),整合IK分词器和安装Kibana
java·大数据·elasticsearch·搜索引擎·全文检索·jenkins·es
向哆哆37 分钟前
Eclipse Java 开发调优:如何让 Eclipse 运行更快?
java·ide·eclipse
爱晒太阳的小老鼠43 分钟前
策略模式-枚举实现
java·策略模式
77tian1 小时前
设计模式的原理及深入解析
java·开发语言·单例模式·设计模式·代理模式·享元模式·原型模式
会飞的架狗师1 小时前
【Spring Cloud Gateway】Nacos整合遇坑记:503 Service Unavailable
java·开发语言
重生之后端学习3 小时前
02-前端Web开发(JS+Vue+Ajax)
java·开发语言·前端·javascript·vue.js
nuclear20113 小时前
使用Python将 Excel 中的图表、形状和其他元素导出为图片
python·excel·将excel图表转换为图片·将excel文本框转换为图片
三少的笔记3 小时前
Windows中PDF TXT Excel Word PPT等Office文件在预览窗格无法预览的终级解决方法大全
pdf·word·excel