这是我的代码。我正在尝试使用一些具有颜色和自动调整的单元格将 gridview 导出到 excel 中。这里的问题是一切正常,除了在后台运行的 EXCEL.EXE。但是,如果我排除了 Autofit 和着色单元格的代码,则 Excel 任务将终止。
下面是我的代码
protected void xlsWorkBook()
{
try
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Workbooks oWBs;
Excel.Worksheet oSheet;
Excel.Range oRange;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = false;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWBs = oXL.Workbooks;
oWB = oWBs.Add(1);
oSheet = oWB.ActiveSheet;
DataGridView dataGridExport = new DataGridView();
dataGridExport.DataSource = GetData();
bool isColorCells = false;
oRange = oSheet.Cells;
for (int k = 1; k <= dataGridExport.Columns.Count; k++)
{
//oRange.set_Item(1, k, dataGridExport.Columns[k - 1].Name);
oSheet.Cells[1, k] = dataGridExport.Columns[k - 1].Name;
((dynamic)oSheet.Cells[1, k]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SteelBlue);
}
for (int i = 1; i <= dataGridExport.Rows.Count; i++)
{
for (int k = 1; k <= dataGridExport.Rows[i - 1].Cells.Count; k++)
{
if (Convert.ToString(dataGridExport.Rows[i - 1].Cells[k - 1].Value) != string.Empty)
{
//oRange.set_Item(i + 1, k, dataGridExport.Rows[i - 1].Cells[k - 1].Value);
oSheet.Cells[i + 1, k] = dataGridExport.Rows[i - 1].Cells[k - 1].Value;
}
if ((isColorCells) && (dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb() != 0))
{
//oRange.Interior.Color = Color.Red;
((dynamic)oSheet.Cells[i + 1, k]).Interior.Color = ColorTranslator.ToOle(Color.FromArgb(dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb()));
}
}
}
dataGridExport = null;
oSheet.Columns.AutoFit();
//oRange.EntireColumn.AutoFit();
// Save the sheet and close
//oSheet = null;
//oRange = null;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xlsx";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
oWB.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
}
GC.Collect();
GC.WaitForPendingFinalizers();
oWB.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWBs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
this.Cursor = Cursors.Default;
}