遍歷xlsx文件批量生成二維碼

package com.ttcf.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


public class test {


@SuppressWarnings("unchecked")
public static void test(String name, String phone) {
int width = 300;
int height = 300;
String format = "png";

//在地址後面拼接號碼之後生產二維碼的url
String content = "https://ttcf.cheleu.com/static/package/login.html?phone="+phone;
//定義二維碼的參數
Map map = new HashMap();
//設置編碼
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
//設置糾錯等級
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
map.put(EncodeHintType.MARGIN, 2);

try {
//生成二維碼
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);

//生成二維碼存放的地址
Path file = new File("C:/Users/Administrator/Desktop/市場推廣/"+name+".png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
 

 

//main方法測試
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {

//獲取本地的xlsx
File file = new File("C:/Users/Administrator/Desktop/hh.xlsx");
InputStream input = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(input);
Sheet sheet = wb.getSheetAt(0); // 獲得第一個表單

//開始遍歷
Iterator<Row> rows = sheet.rowIterator(); // 獲得第一個表單的迭代器
while (rows.hasNext()) {
Row row = rows.next(); // 獲得行數據
String name = null;
String phone = null;
for (int j = 0; j < 2; j++) {
Cell cell = row.getCell(j);
if(null != cell){
if(cell.getCellType() == CellType.NUMERIC){
DecimalFormat df = new DecimalFormat("0");
phone = df.format(cell.getNumericCellValue());
}else{
name = cell.toString();
}
}
}
if(null != name && null != phone){
test(name, phone);
}
}
}

}
 

 

 

pom.xml(添加版本依賴)

 


<!-- 自動生成二維碼 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>

 

 

 

xlsx文件

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章