1.如何给excel添加二维码
其实二维码就是一张图片,把生成的二维码作为图片返回给excel对应的栏位就可以达到目的,代码如下:
点击查看代码
public Bitmap GetBitmap(string code,ExcelPackage package)
{
var sheet = package.Workbook.Worksheets[0];
// 创建QR码生成器
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
// 生成二维码图片
Bitmap qrImage = qrCode.GetGraphic(20, Color.Black, Color.White, true);
// 将二维码保存为图片文件
string qrCodeFilePath = $"{System.AppDomain.CurrentDomain.BaseDirectory}Qrcode";
if (!System.IO.Directory.Exists(qrCodeFilePath))
{
System.IO.Directory.CreateDirectory(qrCodeFilePath);
}
qrCodeFilePath += $"\\{code}_qrcode.png";
qrImage.Save(qrCodeFilePath, System.Drawing.Imaging.ImageFormat.Png);
var fileInfo = new FileInfo(qrCodeFilePath);
//将二维码图片添加到Excel中
// 定位到第16行
var startRow = 17;
var startCol = 2;
var endRow = 19;
var endCol = 3;
var pictureIndex = sheet.Drawings.AddPicture("picture", fileInfo);
//删除临时文件
System.IO.File.Delete(qrCodeFilePath);
//var pictureIndex = sheet.Drawings.AddPicture("picture", qrImage);
// 设置二维码的起始单元格位置
var qrCodeTopLeft = sheet.Cells[startRow, startCol];
var qrCodeBottomRight = sheet.Cells[endRow, endCol];
// 设置二维码的位置和大小
pictureIndex.SetPosition(qrCodeTopLeft.Start.Row - 1, qrCodeTopLeft.Start.Column - 1,
qrCodeBottomRight.Start.Row - qrCodeTopLeft.Start.Row + 1,
qrCodeBottomRight.Start.Column - qrCodeTopLeft.Start.Column + 1);
pictureIndex.SetSize(200, 200);
return qrImage;
}