1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 数据转换成二维码并导出进Excel中和导入时解码二维码反转成数据

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

时间:2020-11-02 05:50:41

相关推荐

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

数据转换成二维码并导出进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.mon.BitMatrix;import com.mon.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 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();}}

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。