1

我正在导出到 excel。但我也必须在 excel 单元格中导出图像。

public void GenerateAndSaveExcel(DataSet ds)
{
    try
    {
        bool excelCreated = CreateExcelApplication();
        bool workbookCreated = CreateWorkBook();
        if (excelCreated && workbookCreated)
        {
            bool workSheetAdded = AddWorkSheet();
            if (workSheetAdded)
            {
                CreateHeader(ds.Tables[0].Columns);
                AddRows(ds.Tables[0].Rows, ds.Tables[0].Columns);

                Save(@"C:\Worksheet1.xlsx");

            }
        }
        else
        {

        }
    }
    catch (System.UnauthorizedAccessException)
    {

    }
    catch (System.Runtime.InteropServices.COMException)
    {

    }
    catch (System.IO.IOException)
    {

    }
    finally
    {
        excelApp.Quit();
        workBook = null;
        workSheet = null;
        Dispose();
    }
}

这里说我有 ID、Name、SEREENSHOT1、SEREENSHOT2 等列。其中 SEREENSHOT1,SEREENSHOT2 是图像字节数组。

我在 AddRows 方法中进行所有计算

public void AddRows(DataRowCollection dataRows, DataColumnCollection colMap)
{
    Microsoft.Office.Interop.Excel.Worksheet workSheet = workSheets.First();
    string startIndex = "B1";
    Microsoft.Office.Interop.Excel.Range range = workSheet.get_Range(startIndex, Missing.Value);

    int rowIndex = 2;
    foreach (var row in dataRows)
    {
        int colIndex = 1;
        foreach (DataColumn column in colMap)
        {
            range = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, colIndex++];
            object value = ((System.Data.DataRow)(row)).ItemArray[column.Ordinal];
            if (column.ColumnName != "SCREENSHOT1" && column.ColumnName != "SCREENSHOT2")
            {
                range.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, value);
            }
            if (column.ColumnName == "SCREENSHOT1" && !string.IsNullOrEmpty(value.ToString()))
            {
                string path = ConfigurationSettings.AppSettings["imagepathPath"]
                           + @"\img" + ((System.Data.DataRow)(row)).ItemArray[0].ToString() + "SRN1" + ".jpg";
                workSheet.Shapes.AddPicture(path, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 10, 10, 200, 200);
            }
            if (column.ColumnName == "SCREENSHOT2" && !string.IsNullOrEmpty(value.ToString()))
            {
                string path = ConfigurationSettings.AppSettings["imagepathPath"]
                           + @"\img" + ((System.Data.DataRow)(row)).ItemArray[0].ToString() + "SRN1" + ".jpg";
                workSheet.Shapes.AddPicture(path, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 10, 10, 100, 100);
            }
        }
        rowIndex++;
    }
}

这里一切正常,即使图像也来了......但是如何确定图像的位置单元格。

现在图像来了,但不在单元格中,请帮助。在这里我只能使用互操作。我想将图像放入单元格中

4

0 回答 0