数据转换成二维码并导出进Excel中和导入时解码二维码反转成数据

  • 第一步在maven中配置需要的二维码jar包
    • 1.1 谷歌提供的帮助类
    • 1.2 关于二维码的工具类
    • 1.3 测试类
    • 第二步 在Excel中对应上你的数据
    • 导入的时候读取并解码Excel中的二维码

第一步在maven中配置需要的二维码jar包

这是谷歌提供的 一般使用这个也够用了。

  <dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.0</version></dependency>

1.1 谷歌提供的帮助类

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;/*** 谷歌提供的帮助类* * @author lenovo**/
public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white}}}this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}public byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}image.getRaster().getDataElements(left, top + y, width, 1, row);return row;}public byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];image.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}public boolean isCropSupported() {return true;}public LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}public boolean isRotateSupported() {return true;}public LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);}}

1.2 关于二维码的工具类

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/*** 工具类* @author lenovo**/
public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int WIDTH = 60;// LOGO高度private static final int HEIGHT = 60;private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {Hashtable hints = new Hashtable();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,hints);int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入图片QRCodeUtil.insertImage(image, imgPath, needCompress);return image;}private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println("" + imgPath + "   该文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = HEIGHT;}Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(image, 0, 0, null); // 绘制缩小后的图g.dispose();src = image;}// 插入LOGOGraphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(src, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}/*** 生成二维码encode* @param content* @param imgPath* @param destPath* @param needCompress* @throws Exception*/public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);mkdirs(destPath);// String file = new Random().nextInt(99999999)+".jpg";// ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));ImageIO.write(image, FORMAT_NAME, new File(destPath));}public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);return image;}public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath) throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}// 被注释的方法/** public static void encode(String content, String destPath, boolean* needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,* needCompress); }*/public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);ImageIO.write(image, FORMAT_NAME, output);}public static void encode(String content, OutputStream output) throws Exception {QRCodeUtil.encode(content, null, output, false);}/*** 解析二维码decode* @param file* @return* @throws Exception*/public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}}

1.3 测试类

public class QrCodeTest {public static void main(String[] args) throws Exception {//如果要扫描之后跳转链接的话,内容改成链接路径就可以了String text = "你好";// 嵌入二维码的图片路径String imgPath = "C:/Users/lenovo/Desktop/X.jpg";// 生成的二维码的路径及名称String destPath = "C:/Users/lenovo/Desktop/Smile.jpg";// 生成二维码true:表示将嵌入二维码的图片进行压缩,如果为“false”则表示不压缩。QRCodeUtil.encode(text, imgPath, destPath, true);// 解析二维码String str = QRCodeUtil.decode(destPath);// 打印出解析出的内容System.out.println("生成成功");}}

第二步 在Excel中对应上你的数据

/*** @Title: export* @Description: <p>导出数据</p>* @param response 响应* @param title 表名  * @param rowsName  行标题* @param dataList  数据列表* @throws Exception 抛出异常* @version 1.0* @date 2018年8月28日下午4:00:53*/@SuppressWarnings("deprecation")public static void export(HttpServletResponse response,String title ,String[] rowsName,List<Object[]> dataList) throws Exception {try {HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象HSSFSheet sheet = workbook.createSheet(title); // 创建工作表// 产生表格标题行HSSFRow rowm = sheet.createRow(0);HSSFCell cellTiltle = rowm.createCell(0);// sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);// 获取列头样式对象HSSFCellStyle style = getStyle(workbook); // 单元格样式对象//sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowsName.length - 1)));//cellTiltle.setCellStyle(columnTopStyle);//cellTiltle.setCellValue(title);// 定义所需列数int columnNum = rowsName.length;HSSFRow rowRowName = sheet.createRow(0); // 在索引2的位置创建行(最顶端的行开始的第二行)// 将列头设置到sheet的单元格中for (int n = 0; n < columnNum; n++) {HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型HSSFRichTextString text = new HSSFRichTextString(rowsName[n]);cellRowName.setCellValue(text); // 设置列头单元格的值cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式}// 将查询出的数据设置到sheet对应的单元格中for (int i = 0; i < dataList.size(); i++) {Object[] obj = dataList.get(i);// 遍历每个对象HSSFRow row = sheet.createRow(i + 1);// 创建所需的行数for (int j = 0; j < obj.length; j++) {HSSFCell cell = null; // 设置单元格的数据类型if (j == 0) {if(obj[j].toString().equals("合计(元)")){cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);cell.setCellValue(obj[j].toString());}else{cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);cell.setCellValue(i + 1);}} else {cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);if (!"".equals(obj[j]) && obj[j] != null) {if(j%6==0) {String text=obj[j].toString();// 生成的二维码的路径及名称String destPath = "C:/Users/lenovo/Desktop/QRcode.jpg";// 生成二维码true:表示将嵌入二维码的图片进行压缩,如果为“false”则表示不压缩。QRCodeUtil.encode(text, null, destPath, true);BufferedImage bufferImg = null;// 图片// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArrayByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();// 将图片读到BufferedImagebufferImg = ImageIO.read(new File("C:/Users/lenovo/Desktop/QRcode.jpg"));// 将图片写入流中ImageIO.write(bufferImg, "png", byteArrayOut);// 利用HSSFPatriarch将图片写入EXCELHSSFPatriarch patriarch = sheet.createDrawingPatriarch();/*** 该构造函数有8个参数 前四个参数是控制图片在单元格的位置,分别是图片距离单元格left,top,right,bottom的像素距离* 后四个参数,前连个表示图片左上角所在的cellNum和 rowNum,后天个参数对应的表示图片右下角所在的cellNum和 rowNum,* excel中的cellNum和rowNum的index都是从0开始的**/// 图片一导出到单元格B2中HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 6, 1+i, (short) 7, 2+i);// 插入图片patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));} else {cell.setCellValue(obj[j].toString()); // 设置单元格的值}}else{cell.setCellValue("");}}cell.setCellStyle(style); // 设置单元格样式}}if (workbook != null) {try {String fileName =  title + "-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");String headStr = "attachment; filename=\"" + fileName + "\"";//response.setContentType("APPLICATION/OCTET-STREAM");response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setHeader("Content-Disposition", headStr);OutputStream out = response.getOutputStream();workbook.write(out);out.close();} catch (IOException e) {LOGGER.error(e.getMessage(),e);}finally{//workbook.close();}}} catch (Exception e) {LOGGER.error(e.getMessage(),e);}}

因为Excel工具类都不大一样,所以这里只列出具体在Excel方法中关于二维码的处理,以上数据转换成二维码并导出已完成。

导入的时候读取并解码Excel中的二维码

这里同样也是说的转换读取的方法,没有具体的Excel实现。这里是导入的时候读取二维码并转换成数据

for (int i = 1; i <= rowNum; i++) {//获得第i行对象Row row = sheet.getRow(i);String fromadress = "";String waitsigndata="";//获得获得第i行第0列的 String类型对象Cell cell = row.getCell((short) 1);if (cell != null) {fromadress = cell.getStringCellValue().trim();}cell = row.getCell((short) 6);if(cell != null ){try {//获取到第一张二维码HSSFPictureData picture  = (HSSFPictureData) wookbook.getAllPictures().get(i-1);//转换byte[] data = picture.getData();//因为获取必须要存一个路径String path = "C:/Users/lenovo/Desktop/QRcode"+i+".jpg" ;FileImageOutputStream out = new FileImageOutputStream(new File(path));out.write(data,0, data.length);out.close();//解码String signdata = QRCodeUtil.decode(path);} catch (Exception e) {e.printStackTrace();}}

我也是自己百度加理解然后完成实现的。如果有更好的方法欢迎留言。

数据转换成二维码并导出进Excel中和导入时解码二维码反转成数据相关推荐

  1. java - poi递归导出树结构Excel,导入树结构Excel,树结构递归查询,新增,修改,删除

    工作中设计树结构增删改查,导入,导出操作,搜索 POI导入导出树结构Excle 相关博客较少,故写博客用以记录分享. 文章目录 一.表结构设计,导入导出模板. 二.递归查询树结构 1.思路如下 2.代 ...

  2. 关于数据导出到Excel或wps时避免自动转成科学计数法的处理

    SELECT '=T("'+字段+'")' from table 在显示的字段内容前加了 '=T("',在后面也加了'")'.在这这里T()是Excel的函数, ...

  3. 如何将html表格导出到excel,html 页面导出到excel表格数据类型-如何将html里面的table导出成excel...

    怎么把html导出到excel表格 1先,我们打开要转换成THML的表格文件.下是我用的WPS2019版截图,EXCEL软件操作上差不多 2.接下来,点击左上角的[文件] 3.在[文件]菜单里找到并点 ...

  4. php导出数字成科学计数法,php导出excel长数字显示成科学计数法格式的解决方案...

    php导出excel长数字显示成科学计数法格式的解决方案 首先,我们了解一下excel从web页面上导出的原理.当我们把这些数据发送到客户端时,我们想让客户端程序(浏览器)以excel的格式读取它,所 ...

  5. python实现sqlserver表导出为excel

    文章目录 前言 一.将sqlserver导出为excel 二.当表中数据量巨大时 三.加入定时器 四.打包成zip压缩包 五.删除某一目录下的所有文件 六.完整代码实例 七.Python打包EXE 八 ...

  6. ABAP Excel处理-内表导出为Excel文件

    目录 一.概述 二.内表导出为Excel文件的实现 1. OLE下载内表数据为Excel文件 2. DOI下载内表数据为Excel文件 3. 生成文本形式的Excel(.xls或.csv) 4. 标准 ...

  7. Functional ALV系列 (06) - 数据导出至Excel

    方法1:利用cl_salv_export_tool_xls 类实现导出 ALV 数据导出至 Excel,其实就是将 ALV 对应的内表数据导出至 Excel.大家常见的 GUI_DOWNLOAD 函数 ...

  8. 利用免费工具爬取关键词(数据)的豆瓣读书数据——八爪鱼爬取数据并导出到Excel/Mysql数据库设置示例——关键词:爬虫、读书、实用

    目录 原始需求 需求解读 所需软件配置 软件介绍 八爪鱼 Excel Navicat Mysql 数据采集及保存 步骤1  探索搜索页面规律 步骤二  八爪鱼批量生成链接,添加参数(前缀+尾巴) 步骤 ...

  9. 使用js代码将HTML Table导出为Excel

    使用js代码将HTML Table导出为Excel的方法: 直接上源码 <html> <head> <meta http-equiv="Content-Type ...

最新文章

  1. 系统集成知识点整理(五)质量管理
  2. 海量java等互联网相关电子图书分享
  3. 从send函数和sendto函数参数的不同看TCP和UDP的差别
  4. How to extend unallocated space to an existing partition on linux? | 如何在 linux 上扩展已有分区至未分配空间?
  5. 某自媒体发布“抢小孩”视频,最高近25万次点赞,结果竟是自导自演!
  6. 什么是ie浏览器_关于几款电脑浏览器的使用感受,你用过吗?
  7. [导入]七大千年数学难题
  8. mac系统的UTF-8 BOM编码
  9. 水星d128路由器虚拟服务器,幻影D128路由器怎么设置?
  10. SSM整合尚硅谷Spring
  11. 明星危机公关应该怎么做?
  12. GMT中文字体显示配置
  13. mongoDB conf 文件配置详解
  14. 系统级程序设计第二次作业
  15. 常见积分和导数的推导
  16. 小王的架构师之旅路----面试
  17. 从libc-2.27.so[7ff3735fd000+1e7000]崩溃回溯程序段错误segfault
  18. 程序员不得不学的养生秘诀
  19. HeadFrist设计模式学习之做一个万能遥控器(命令模式)
  20. 破局红海市场?盘点那些传统企业要学会的超级产品战略方法论

热门文章

  1. 06 | 指令跳转:原来if...else就是goto
  2. 【Android App】GPS获取定位经纬度和根据经纬度获取详细地址讲解及实战(附源码和演示 超详细)
  3. 2017年的奋斗目标
  4. Unity 物理系统 -- 刚体简介
  5. 三校生模拟计算机试题,三校生高考计算机模拟试卷(一).doc
  6. oracle客户端没有sqlldr命令,关于oracle的sqlldr或sqlplus命令没响应的问题
  7. C语言:求1000以内的完数
  8. WordPress DUX5.0大前端主题模板
  9. 离散数学及其应用学习笔记——主定理(Master Theorem)的证明
  10. 关于WEB端实现电子海图研究之思路