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;
}