1 Star 0 Fork 0

jiangstack/AnyErCode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Form1.cs 3.97 KB
一键复制 编辑 原始数据 按行查看 历史
jiangstack 提交于 2024-06-03 01:33 . 增加进度条功能
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using QRCoder;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace AnyErCode
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void selectFileBtn_Click(object sender, EventArgs e)
{
Console.WriteLine("button1_Click");
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "(*.xls)|*.xlsx"; // 设置文件过滤器,可以根据需要调整
openFileDialog.Title = "选择Excel文件";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog.FileName; // 将选择的文件路径赋值给TextBox
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
GenerateQRCodeFromExcel();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void GenerateQRCodeFromExcel()
{
string filePath = textBox1.Text;
if (string.IsNullOrEmpty(filePath))
{
MessageBox.Show("请先选择路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// 使用NPOI读取Excel
IWorkbook workbook;
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
workbook = filePath.EndsWith(".xls") ? new HSSFWorkbook(fileStream) : new XSSFWorkbook(fileStream);
}
ISheet sheet = workbook.GetSheetAt(0); // 假设我们要处理第一个工作表
var directoryPath = Path.GetDirectoryName(filePath); // 获取Excel文件的目录路径
if (directoryPath is null)
{
return;
}
//sheet.FirstRowNum
progressBar1.Maximum = sheet.LastRowNum;
progressBar1.Step = 1;
// 遍历每一行,假设文本在第一列
for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
{
IRow row = sheet.GetRow(rowIndex);
if (row != null)
{
string qrCodeFilePath = "";
ICell cell = row.GetCell(0); // 假设文本在第一列
if (cell != null && cell.CellType == CellType.String)
{
string cellValue = cell.StringCellValue;
// 生成二维码
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(cellValue, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
// 保存二维码到Excel文件的同级目录
qrCodeFilePath = Path.Combine(directoryPath, $"{cellValue.Replace(" ", "_")}.png");
using (var codeImage = qrCode.GetGraphic(5))
{
codeImage.Save(qrCodeFilePath);
progressBar1.Value = rowIndex;
label2.Text = $"{rowIndex * 100 / sheet.LastRowNum}%";
}
}
if (rowIndex == 1)
{
using (var stream = new FileStream(qrCodeFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
}
}
workbook.Close(); // 关闭工作簿
MessageBox.Show($"二维码已经生成在{directoryPath}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/jiangstack/AnyErCode.git
[email protected]:jiangstack/AnyErCode.git
jiangstack
AnyErCode
AnyErCode
master

搜索帮助