C# 實現商品數據導入,Excel 中固定列包含商品圖片,需提取第一行圖片。
using Excel = Microsoft.Office.Interop.Excel;
public Image ExtractFirstPicture(string filePath, int pictureColumn = 3) // 1-based
{
Excel.Application app = new Excel.Application();
app.Visible = false;
Excel.Workbook wb = app.Workbooks.Open(filePath);
Excel.Worksheet ws = (Excel.Worksheet)wb.Sheets[1];
// 遍歷圖片集合,找到位於指定列、第一行的圖片
foreach (Excel.Shape shape in ws.Shapes)
{
if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoPicture)
{
// 獲取圖片左上角單元格地址
Excel.Range topLeft = shape.TopLeftCell;
if (topLeft.Row == 1 && topLeft.Column == pictureColumn)
{
// 複製圖片到剪貼板再取出
shape.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);
if (Clipboard.ContainsImage())
{
Image img = Clipboard.GetImage();
wb.Close(false);
app.Quit();
return img;
}
}
}
}
wb.Close(false);
app.Quit();
return null;
}
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; // .xlsx
using NPOI.HSSF.UserModel; // .xls
public Image ExtractWithNPOI(string filePath, int rowIdx = 0, int colIdx = 2) // 0-based
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
IWorkbook wb = WorkbookFactory.Create(fs);
ISheet sheet = wb.GetSheetAt(0);
// NPOI 直接提取圖片較繁瑣,需解析繪圖關係
// 簡易方式:若圖片作為單元格背景或批註,可嘗試
// 完整提取需遍歷 sheet.GetDrawingPatriarch().GetShapes()
// 此處略過詳細代碼,參考 NPOI 官方示例 "ExtractImages"
}
return null;
}
// EPPlus 示例
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
public Image ExtractWithEPPlus(string filePath, int row = 1, int col = 3)
{
using (var pkg = new ExcelPackage(new FileInfo(filePath)))
{
var ws = pkg.Workbook.Worksheets[0];
foreach (var drawing in ws.Drawings)
{
if (drawing is ExcelPicture pic)
{
// 檢查圖片錨點是否在目標單元格
if (pic.From.Row == row && pic.From.Column == col)
{
return pic.Image; // 直接返回 System.Drawing.Image
}
}
}
}
return null;
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| Interop.Excel | 功能最全,完美兼容 .xls/.xlsx | 需安裝 Office,佔用大,非線程安全,不適合服務端 | 桌面端、已有 Office 環境 |
| NPOI | 開源、跨平台、無依賴、支持 .xls/.xlsx | 圖片提取 API 較底層,需較多代碼 | 服務端、Linux 容器、批量處理 |
| EPPlus / ClosedXML | API 現代、圖片提取簡單 | 僅支持 .xlsx,EPPlus 5+ 需商業授權 | .xlsx 為主、追求開發效率 |
TopLeftCell/From)定位所在行列。ws.UsedRange 確定實際區域。