C#Excel Interop Shapes.AddPicture图像大小不正确第二次尝试导出到Excel文件

时间:2017-01-22 09:09:26

标签: c# .net excel excel-interop

目前我正在使用Excel.Interop.Shapes.AddPicture方法将图片添加到我的Excel文件中。

最初,所有工作都很好,首先编译程序并将其导出到excel中。但是第二次导出到excel等等,图片变得越来越小,随机变得越来越大,不符合我在Excel对象上设置的宽度和高度。

它应该是我导出到excel的所有内容,图像大小将是270 x 198.但是如果我重新编译程序并导出,第一次导出文件的图像一切都很好,但第二次尝试导出文件等等随着运行程序,图像大小将随机变得越来越大。

如果我的导出方法出错了,请告诉我。

以下是我用于导出到Excel的代码:

private void btnPhotoExcel_Click(object sender, EventArgs e)
{
    Excel.Workbooks objBooks;
    Excel.Sheets objSheets;
    Excel._Worksheet objSheet = new Excel.Worksheet();
    Excel.Range range;
    // Getting the location and file name of the excel to save from user.
    SaveFileDialog saveDialog = new SaveFileDialog();
    saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
    saveDialog.FilterIndex = 2;

    // Declare of Excel Instance
    objApp = new Excel.Application();
    objBooks = objApp.Workbooks;
    objBook = objBooks.Add(Type.Missing);
    objSheets = objBook.Worksheets;

    List<String> photoList = new List<string>();
    List<String> photoDescriptionList = new List<string>();

    for (int i = 0; i < photoDataGridView.Rows.Count; i++)
    {
        if (photoDataGridView.Rows[i].Cells["Photo Path"].Value != null)
        {
            photoList.Add(photoDataGridView.Rows[i].Cells["Photo Path"].Value.ToString());
            photoDescriptionList.Add(photoDataGridView.Rows[i].Cells["Photo Descriptions"].Value.ToString());
        }
    }

    // Check file exist
    bool isFileExist = false;

    if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        try
        {
            if (File.Exists(saveDialog.FileName + ".xlsx"))
            {
                DialogResult result = MessageBox.Show("File '" + saveDialog.FileName + ".xlsx" + "' Already Exist.\nAre You Sure To Overwrite?", "Microsoft Excel",
 MessageBoxButtons.OKCancel);
                switch (result)
                {
                    case DialogResult.OK:
                        {
                            isFileExist = false; // Does not exist file. Create new one
                            break;
                        }
                    case DialogResult.Cancel:
                        {
                            isFileExist = true; // User Cancel To Overwrite
                            break;
                        }
                }
            }
            else
            {
                isFileExist = false; // Does not exist file. Create new one
            }

            if (!isFileExist)
            {
                #region Photo Report Export Excel
                int row = 120;
                int column = 120;        // If got added new column, then need to minus 1 from here
                // Instantiate Excel and start a new workbook.
                objSheet = (Excel._Worksheet)objSheets.get_Item(1);
                objSheet.Name = "Maintenance & Activity Photos";

                // Get the range where the starting cell has the address
                // m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
                range = objSheet.get_Range("A1", Missing.Value);
                range = range.get_Resize(row, column);

                // Create an array.
                string[,] saRet = new string[row + 1, column];

                #region Header
                // Header
                saRet[0, 0] = "LOJI RAWATAN AIR BANGKAP";
                objSheet.get_Range("A1", "C1").Merge();
                objSheet.Range["A1", "A1"].Font.Bold = true;
                objSheet.Range["A1", "A1"].Font.Size = 22;
                objSheet.Range["A1", "A1"].Font.Color = Color.Blue;
                objSheet.get_Range("A1", "A1").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                objSheet.Columns["A"].ColumnWidth += 70;
                objSheet.get_Range("A1", "A2").Merge();

                saRet[2, 0] = "Operation & Maintenance: Harmony Water Sendirian Berhad";
                objSheet.Range["A3", "A3"].Font.Size = 12;
                objSheet.get_Range("A3", "C3").Merge();
                objSheet.get_Range("A3", "A3").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

                saRet[2, 3] = "Date: Wednesday, 11 January 2017";
                objSheet.Range["A3", "A3"].Font.Size = 12;
                objSheet.get_Range("A3", "A3").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

                saRet[3, 0] = "Activity & Maintenance Photos";
                objSheet.Range["A4", "A4"].Font.Size = 12;
                objSheet.Range["A4", "A4"].Font.Underline = true;
                objSheet.get_Range("A4", "B4").Merge();
                objSheet.get_Range("A4", "A4").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
                #endregion

                #region Main Content Photo and Description
                for (int k = 0; k < photoList.Count; k++ )
                {
                    string pDescription = photoDescriptionList[k].ToString();
                    if (pDescription == "")
                    {
                        pDescription = "NULL";
                    }
                    if (k == 0 || k == 1 || k == 2 || k == 3)           // First Page
                    {
                        #region First Page

                        if(k == 0)
                        {
                            // First Page, First Row (Left Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 85, 270, 198);
                            saRet[18, 0] = pDescription; // Picture Description
                            objSheet.Range["A19", "A19"].Font.Size = 10;
                            objSheet.get_Range("A19", "B19").Merge();
                            objSheet.get_Range("A19", "A19").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                            objSheet.get_Range("A1", "A20").Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Left
                            objSheet.get_Range("D1", "D20").Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Right
                            objSheet.get_Range("A20", "D20").Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Bottom
                        }
                        else if(k == 1)
                        {
                            // First Page, First Row (Right Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 420, 85, 270, 198);
                            saRet[18, 2] = pDescription; // Picture Description
                            objSheet.Range["C19", "C19"].Font.Size = 10;
                            objSheet.get_Range("C19", "D19").Merge();
                            objSheet.get_Range("C19", "C19").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                        }
                        else if(k == 2)
                        {
                            // First Page , Second Row (Left Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 330, 270, 198);
                            saRet[34, 0] = pDescription; // Picture Description
                            objSheet.Range["A35", "A35"].Font.Size = 10;
                            objSheet.get_Range("A35", "B35").Merge();
                            objSheet.get_Range("A35", "A35").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                            objSheet.get_Range("A20", "A36").Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Left
                            objSheet.get_Range("D20", "D36").Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Right
                            objSheet.get_Range("A36", "D36").Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Bottom
                        }
                        else if(k == 3)
                        {
                            // First Page, Second Row (Right Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 420, 330, 270, 198);
                            saRet[34, 2] = pDescription; // Picture Description
                            objSheet.Range["C35", "C35"].Font.Size = 10;
                            objSheet.get_Range("C35", "D35").Merge();
                            objSheet.get_Range("C35", "C35").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                        }
                        #endregion
                    }
                    else if (k == 4 || k == 5 || k == 6 || k == 7)     // Second Page
                    {
                        #region Second Page
                        if (k == 4)
                        {
                            // Second Page, First Row (Left Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 375 + (1 * 245 - (1 * 5)), 270, 198);
                            saRet[53, 0] = pDescription; // Picture Description
                            objSheet.Range["A54", "A54"].Font.Size = 10;
                            objSheet.get_Range("A54", "B54").Merge();
                            objSheet.get_Range("A54", "A54").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                            objSheet.get_Range("A40", "D40").Borders.get_Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Top
                            objSheet.get_Range("A40", "A55").Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Left
                            objSheet.get_Range("D40", "D55").Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Right
                            objSheet.get_Range("A55", "D55").Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Bottom

                        }
                        else if(k == 5)
                        {
                            // Second Page, First Row (Right Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 420, 375 + (1 * 245 - (1 * 5)), 270, 198);
                            saRet[53, 2] = pDescription; // Picture Description
                            objSheet.Range["C54", "C54"].Font.Size = 10;
                            objSheet.get_Range("C54", "D54").Merge();
                            objSheet.get_Range("C54", "C54").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

                        }
                        else if(k == 6)
                        {
                            // Second Page, Second Row (Left Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 375 + (2 * 245 - (2 * 5)), 270, 198);
                            saRet[69, 0] = pDescription; // Picture Description
                            objSheet.Range["A70", "A70"].Font.Size = 10;
                            objSheet.get_Range("A70", "B70").Merge();
                            objSheet.get_Range("A70", "A70").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                            objSheet.get_Range("A55", "A71").Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Left
                            objSheet.get_Range("D55", "D71").Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Right
                            objSheet.get_Range("A71", "D71").Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Bottom
                        }
                        else if(k == 7)
                        {
                            // Second Page, Second Row (Right Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 420, 375 + (2 * 245 - (2 * 5)), 270, 198);
                            saRet[69, 2] = pDescription; // Picture Description
                            objSheet.Range["C70", "C70"].Font.Size = 10;
                            objSheet.get_Range("C70", "D70").Merge();
                            objSheet.get_Range("C70", "C70").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

                        }
                        #endregion
                    }
                    else if (k == 8 || k == 9 || k == 10 || k == 11)    // Third Page
                    {
                        #region Third Page
                        if (k == 8)
                        {
                            // Third Page, First Row (Left Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 465 + (3 * 245 - (3 * 5)), 270, 198);
                            saRet[91, 0] = pDescription; // Picture Description
                            objSheet.Range["A92", "A92"].Font.Size = 10;
                            objSheet.get_Range("A92", "B92").Merge();
                            objSheet.get_Range("A92", "A92").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                            objSheet.get_Range("A78", "D78").Borders.get_Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Top
                            objSheet.get_Range("A78", "A93").Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Left
                            objSheet.get_Range("D78", "D93").Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Right
                            objSheet.get_Range("A93", "D93").Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Bottom

                        }
                        else if (k == 9)
                        {
                            // Third Page, First Row (Right Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 420, 465 + (3 * 245 - (3 * 5)), 270, 198);
                            saRet[91, 2] = pDescription; // Picture Description
                            objSheet.Range["C92", "C92"].Font.Size = 10;
                            objSheet.get_Range("C92", "D92").Merge();
                            objSheet.get_Range("C92", "C92").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                        }
                        else if (k == 10)
                        {
                            // Third Page, Second Row (Left Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 465 + (4 * 245 - (4 * 5)), 270, 198);
                            saRet[107, 0] = pDescription; // Picture Description
                            objSheet.Range["A108", "A108"].Font.Size = 10;
                            objSheet.get_Range("A108", "B108").Merge();
                            objSheet.get_Range("A108", "A108").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                            objSheet.get_Range("A93", "A109").Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Left
                            objSheet.get_Range("D93", "D109").Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Right
                            objSheet.get_Range("A109", "D109").Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; // Draw on the Bottom
                        }
                        else if (k == 11)
                        {
                            // Third Page, Second Row (Right Photo)
                            objSheet.Shapes.AddPicture(@"" + photoList[k].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue, 420, 465 + (4 * 245 - (4 * 5)), 270, 198);
                            saRet[107, 2] = pDescription; // Picture Description
                            objSheet.Range["C108", "C108"].Font.Size = 10;
                            objSheet.get_Range("C108", "D108").Merge();
                            objSheet.get_Range("C108", "C108").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                        }
                    }
                    #endregion

                }
                objSheet.Columns["C"].ColumnWidth += 15; // Extend the column "C" Width
                objSheet.Columns["B"].ColumnWidth = 0;  // Hide Column B which is unused
                #endregion

                // Draw Border
                objSheet.get_Range("A1", "D3").Borders.LineStyle = Excel.XlLineStyle.xlContinuous;  // Draw header border

                objSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;
                // Normal Margins
                objSheet.PageSetup.LeftMargin = objApp.CentimetersToPoints(0.5);
                objSheet.PageSetup.RightMargin = objApp.CentimetersToPoints(0.5);
                objSheet.PageSetup.TopMargin = objApp.CentimetersToPoints(0.5);
                objSheet.PageSetup.BottomMargin = objApp.CentimetersToPoints(0.5);
                objSheet.PageSetup.HeaderMargin = objApp.CentimetersToPoints(0.5);
                objSheet.PageSetup.FooterMargin = objApp.CentimetersToPoints(0.5);
                // Fit Sheet on One Page 
                objSheet.PageSetup.FitToPagesWide = 1;
                objSheet.PageSetup.FitToPagesTall = 1;
                // Set the range value to the array.
                range.set_Value(Missing.Value, saRet);
                objSheet.Columns.AutoFit();
                objApp.DisplayAlerts = false;   // Temporary disable the alert box
                objBook.SaveAs(saveDialog.FileName);
                MessageBox.Show("Excel File Is Saved At :\n" + saveDialog.FileName, "Success");                    
                #endregion
            }
        }
        catch (Exception theException)
        {
            MessageBox.Show(theException.ToString());
            MessageBox.Show("Operation Canceled.", "Failed To Save");
        }
        finally
        {
            photoList.Clear();
            photoDescriptionList.Clear();
            objApp.Quit();
            objBook = null;
            objApp = null;

            // Release All Excel Object
            releaseObject(objSheet);
            releaseObject(objSheets);
            releaseObject(objBook);
            releaseObject(objBooks);
            releaseObject(objApp);
        }
    }
    else
    {
        MessageBox.Show("Operation Canceled.", "Failed To Save");
    }
}

0 个答案:

没有答案