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文档文章,思路基本一致。


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

相关推荐
不爱说话郭德纲11 小时前
告别漫长的HbuilderX云打包排队!uni-app x 安卓本地打包保姆级教程(附白屏、包体积过大排坑指南)
android·前端·uni-app
程序员清风14 小时前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林55115 小时前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
华仔啊21 小时前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing21 小时前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠2 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840822 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide2 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家2 天前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺2 天前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java