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

发布于:2024-07-02 ⋅ 阅读:(17) ⋅ 点赞:(0)

java引包,引的是apache.poi

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>

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

    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给用户,后端不需要存下这个文件。

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

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

把上面的输出流换成

ByteArrayOutputStream bufferedOutputStream = new ByteArrayOutputStream();

然后调用workbook.write写入

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

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


前端微信小程序

// 假设接口请求完成,返回了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文档文章,思路基本一致。


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


网站公告

今日签到

点亮在社区的每一天
去签到