使用C#在Excel上的特定单元格中添加图片

时间:2016-06-03 04:52:18

标签: c# excel-interop

我正在尝试将图像添加到第3行第1列的Excel单元格中,如下所示。编译器给了我一个错误。 我在这里做错了吗?提前感谢您的建议。

Excel.Application xlApp; 
Excel.Workbook wb; 
Excel.Worksheet ws; 
object misValue = System.Reflection.Missing.Value; 
xlApp = new Excel.Application(); 
wb = xlApp.Workbooks.Add(misValue); 
ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); 
ws.Cells[3, 1] = ws.Shapes.AddPicture("C:\\photos\\4a.png", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 75, 75, 350, 50);

2 个答案:

答案 0 :(得分:8)

你必须添加如下图片

Microsoft.Office.Interop.Excel.Range oRange = (Microsoft.Office.Interop.Excel.Range)ws.Cells[3, 1];
float Left = (float)((double)oRange.Left);
float Top = (float)((double)oRange.Top);
const float ImageSize = 32;
ws.Shapes.AddPicture("C:\\pic.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);

答案 1 :(得分:0)

Aspose.Cells API可用于在Excel中使用C#或其他编程语言在特定单元格上添加图片。 Java,C ++等。

为进行演示,请参见下面的 C#代码快照,它们显示了Aspose.Cells API执行后的输入Excel文件和输出Excel文件。代码。 您可以在快照中看到,单元格C12中包含图片。

也请阅读代码中的注释以获取更多帮助。

C#

// Load input Excel file inside Aspose.Cells Workbook object.
Workbook wb = new Workbook("SampleAddPictureInExcelCell.xlsx");

// Access first worksheet.
Worksheet ws = wb.Worksheets[0];

// Access cell C12 by name.
Cell cell = ws.Cells["C12"];

// Add picture in Excel cell.
int idx = ws.Pictures.Add(cell.Row, cell.Column, "D:/Download/Penguins.jpg");

// Access the picture by index.
Picture pic = ws.Pictures[idx];

// Get the column width and row height of the cell in inches.
double w = ws.Cells.GetColumnWidthInch(cell.Column);
double h = ws.Cells.GetRowHeightInch(cell.Row);

// Adjust the picture width and height as per cell width and height.
pic.WidthInch = w;
pic.HeightInch = h;

// Save the workbook in output Excel file.
wb.Save("OutputAddPictureInExcelCell.xlsx", SaveFormat.Xlsx);

快照,显示由Aspose.Cells API生成的输入Excel文件和输出Excel文件。 C12单元格中包含图片。

Snapshot showing the input Excel file and output Excel file generated by Aspose.Cells API. Here cell C12 contains the picture.