大家日常工作当中有时候需要把Excel转换为pdf打印或者转换为图片进行分享,目前有许多在线工具,不过大部分都是需要看激励广告或者收费才可以正常使用,今天给大家分享通过微信小程序自己搭建一个Excel转换工具,随时随地使用免受付费或者看广告的困扰,感兴趣的朋友可以一起来了解一下!
● 开发后端Excel转换接口服务
● 购买云服务器
● 申请域名、SSL证书
● 部署后端接口服务到云服务器并配置SSL证书
● 微信小程序端界面开发
● 微信小程序部署上线
下面针对每一个步骤进行一一介绍。
后端接口这里选择Java编程语法和SpingBoot快速搭建API接口,实现Excel转换为PDF和图片的功能。
首先创建SpringBoot 接口项目,因为属于Java开发者比较基础的知识,这里就不过多介绍了。
创建项目后需要引入Excel转换服务的依赖库。这里使用Maven来管理项目,需要在pom.xml文件引入依赖包。
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>5.1.0</version>
<scope>provided</scope>
</dependency>
注意:为了保证Maven可以正常拉取到依赖库需要在pom.xml 增加以下仓储
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
这里采用小程序上传文件的方式传递到后端接口实现转换的功能。
新建ExcelUtils.java 文件
package com.spring.demo.springbootdemo.utils;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExcelUtils {
/**
*
* @param stream
* @param fileNameOld
* @param type 1 图片、 2 pdf
* @return
*/
public static String exceltofileByFile(InputStream stream, String fileNameOld, String type) {
Date currentDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS"); // 指定日期格式,包含毫秒
String formattedDate = sdf.format(currentDate);
String pathPath = "/mnt/files/" + formattedDate + "_" + fileNameOld;
// 4、最终生成的doc所在的目录,默认是和引入的一个地方,开源时对外提供下载的接口。
saveInputStreamToFile(stream, pathPath);
// 4、最终生成的doc所在的目录,默认是和引入的一个地方,开源时对外提供下载的接口。
String resultSux = ".png";
if(type.equals("2")){
resultSux = ".pdf";
}
String fileName = "resultbyfile" + formattedDate + resultSux;
String desPath = "/mnt/files/" + fileName; // 构造文件名
//加载Excel工作表
Workbook wb = new Workbook();
wb.loadFromFile(pathPath);
//获取工作表
Worksheet sheet = wb.getWorksheets().get(0);
//调用方法将Excel工作表保存为图片
if(type.equals("1")){
sheet.saveToImage(desPath);
}
else if(type.equals("2")){
sheet.saveToPdf(desPath);
}
return fileName;
}
/**
* 保存原始的pdf文件为了方便转换
*
* @param inputStream
* @param filePath
*/
public static void saveInputStreamToFile(InputStream inputStream, String filePath) {
// 使用try-with-resources自动关闭流
try (FileOutputStream outputStream = new FileOutputStream(new File(filePath))) {
byte[] buffer = new byte[1024];
int length;
// 读取输入流并写入到输出流
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
System.out.println("文件保存成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
新建控制器用来提供接口服务,供微信小程序端调用,主要代码如下:
package com.spring.demo.springbootdemo.control;
import com.spring.demo.springbootdemo.utils.ExcelUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* Excel 转换 API
*/
@RestController
@RequestMapping("ExcelAPI")
public class ExcelToFileApi {
/**
* Excel 转换为图片、html、pdf 使用文件的方式
* @param uploadFile
* @return
* @throws IOException
*/
@PostMapping("excelToFile")
public String excelToFile(@RequestPart("file") MultipartFile uploadFile,@RequestParam String type) throws IOException {
if (null == uploadFile) {
return null;
}
// BMP、JPG、JPEG、PNG、GIF
String fileName = uploadFile.getOriginalFilename().toLowerCase();
if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
return null;
}
String result= ExcelUtils.exceltofileByFile(uploadFile.getInputStream(),fileName,type);
// 返回响应实体
return result;
}
}
完成以上步骤,后端服务就基本上搭建完成了。
后端转换服务接口搭建完成后,就需要把后端接口服务部署到云服务器上面,我这边使用的是腾讯云提供的轻量级服务器,目前接口运行还是非常稳定的。
最近赶上腾讯云双十一拼团活动,购买服务器优惠力度非常大,首单购买轻量级云服务器配置为2核2G3M带宽一年仅需要68元,并且加赠三个月。作为部署转换服务接口来说如果并发量不大的情况下是完全够用的。
后端服务部署简要说明:建议购买Centos版本的操作系统,然后给操作系统安装JDK即并且配置环境变量。具体的JDK安装步骤大家可以网上找一下步骤。JDK安装后把后端服务的Jar包上传到服务器,然后使用命令行后台启动即可。当然如果有不清楚的可以评论区沟通交流!
如果你已经有域名并且有SSL证书,本步骤可以跳过。因为微信小程序调用接口需要HTTPS的域名进行调用。所以该步骤是微信小程序上线必备的操作。
大家可以登录腾讯云官网购买域名核的SSL证书的申请,目前免费的SSL证书有效期是三个月,大家注意后续的及时更换过期的SSL证书,避免接口服务不可用,影响线上使用。
腾讯云域名官网:https://dnspod.cloud.tencent.com/
推荐安装nginx来配置SSL证书。这里给大家介绍一下Centos7在线安装nginx的命令
# 依次执行命令
sudo yum install -y epel-release
sudo yum install -y nginx
systemctl status nginx.service
安装成功后配置SSL证书,首先需要把申请通过的SSL证书上传到服务器指定的文件夹,然后直接在nginx.conf文件里面配置即可。
首先看下界面的效果
界面比较简单主要包括上传方式、转换类型、按钮、结果文件展示。首先是选择文件上传后会自动调用后端接口实现文件转换,转换成功后结果文件会体现转换成功后的文件名称。然后点击下载可以下载转换后的PDF或者图片文件。
wxml主要代码文件
<view class="selectSection">
<text class="textmag">上传方式:</text>
<radio-group bindchange="radioChange" class="radio-group">
<label class="radio" wx:for="{{direction}}" wx:key="i">
<icon class="radioIcon {{item.checked?'actIcon':''}}"></icon>
<radio checked="{{item.checked}}" value="{{item.name}}"></radio>{{item.value}}
</label>
</radio-group>
</view>
<view class="selectSection">
<text class="textmag">转换类型:</text>
<radio-group bindchange="radioChangeNew" class="radio-group">
<label class="radio" wx:for="{{changeList}}" wx:key="i">
<icon class="radioIcon {{item.checked?'actIcon':''}}"></icon>
<radio checked="{{item.checked}}" value="{{item.name}}"></radio>{{item.value}}
</label>
</radio-group>
</view>
<view class="container">
<view wx:if="{{directionType==1}}" class="item"> <button style="width: 120px;" class="butss" bindtap="chooseFile">选择Excel</button></view>
<view wx:if="{{directionType==2}}" class="item"> <button style="width: 120px;" class="butss" bindtap="chooseFileNew">生成文件</button></view>
<view class="item"> <button style="width: 90px;" class="butss" bindtap="saveTap">下载</button></view>
<view class="item"> <button style="width: 90px;" class="butss" bindtap="clearTap">清空</button></view>
</view>
<view style="padding: 20px;">
<span style="color: red;font-size: 12px;">温馨提示:转换Excel第一个Sheet为图片、PDF、Html文件</span>
</view>
<view>
<textarea auto-height="true" bindinput="handleInput" class="input-content" value="{{uploadUrl}}" placeholder="请输入Excel文件url" wx:if="{{directionType==2}}"></textarea>
</view>
<view class="instruction" style="padding: 20px;">
<!-- <text>上传的pdf文件:{{pdfPath}}</text> -->
<span style="color: black;">结果文件:{{data}}</span>
</view>
js 主要代码如下:
// 选择文件按钮事件
chooseFileNew: function () {
var that = this;
wx.showLoading({
title: '正在处理中,请稍后...',
});
if (!that.data.uploadUrl) {
wx.showToast({
title: '请先输入pdf的网址',
icon: 'none',
duration: 2000
});
} else {
wx.request({
url: '后台接口url',
method: 'POST', // 请求方法设置为POST
data: {},
name: 'file',
success: function (res) {
if (res.statusCode == "200") {
console.log(res.data);
debugger
that.setData({
imageUrl: res.data,
data: res.data
});
wx.showToast({
title: '转换成功',
icon: 'success',
duration: 2000
});
} else {
wx.showToast({
title: '转换失败,请联系管理员',
icon: 'none',
duration: 2000
});
}
},
fail: function (res) {
wx.showToast({
title: '上传失败',
icon: 'none',
duration: 2000
});
}
});
}
},
// 下载按钮事件
saveTap: function () {
var obj=this.data;
if (obj.imageUrl) {
wx.downloadFile({
url: obj.imageUrl,
success: function (res) {
if (res.statusCode === 200) {
var filePath = res.tempFilePath;
console.log(res.tempFilePath);
// 图片保存
if(obj.changeType===1){
wx.saveImageToPhotosAlbum({
filePath: filePath,
success: function (res) {
wx.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
});
},
fail: function (err) {
console.error(err);
wx.showToast({
title: '保存失败',
icon: 'none',
duration: 2000
});
}
});
}
// pdf 方式
else {
wx.openDocument({
filePath: filePath,
showMenu: true,
success: function (res) {
console.log('打开文档成功')
},
fail: function (res) {
console.log('打开文档失败', res)
}
})}
};
}
}, );
} else {
wx.showToast({
title: '请先上传pdf文件,转换成功后再下载',
icon: 'none',
duration: 2000
});
}
},
转换成功后的效果如下图:
如果需要体验转换效果的话可以搜索【小明工作助手】小程序体验!
微信小程序开发完成后需要通过微信开发者工具把代码上传到云端。
上传成功后就可以登录微信小程序后台。提交版本审核。版本审核通过后,发布你的小程序就可以正常使用了。
以上是完整的微信小程序Excel转换为图片工具的开发流程,大家如果有什么疑问的话,欢迎评论区沟通交流!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。