代码拉取完成,页面将自动刷新
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);
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。