As per the error in the .
For this you need to first find the range to which you want to apply the color. Then apply the color to the range.
Refer the modified code.
C#
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
{
string path = @"C:\Users\dharmendra\Desktop\" + excelFilename + ".xlsx";
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
try
{
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from DataGridView";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
//worksheet.Cells[i + 2, 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
}
// For 1st cell i.e. A
string startRow = "A" + 2; // From 1st row
string endRow = "A" + dataGridView1.Rows.Count; // To last row
worksheet.Range[startRow, endRow].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
workbook.SaveCopyAs(path);
workbook.Saved = true;
}
catch (Exception)
{
}
finally
{
workbook.Close();
app.Quit();
}
}
VB.Net
Public Sub ExportToExcel(ByVal gridviewID As DataGridView, ByVal excelFilename As String)
Dim path As String = "C:\Users\dharmendra\Desktop\" & excelFilename & ".xlsx"
Dim app As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application()
Dim workbook As Microsoft.Office.Interop.Excel._Workbook = app.Workbooks.Add(Type.Missing)
Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = Nothing
Try
app.Visible = True
worksheet = workbook.Sheets("Sheet1")
worksheet = workbook.ActiveSheet
worksheet.Name = "Exported from DataGridView"
For i As Integer = 1 To dataGridView1.Columns.Count + 1 - 1
worksheet.Cells(1, i) = dataGridView1.Columns(i - 1).HeaderText
Next
For i As Integer = 0 To dataGridView1.Rows.Count - 1 - 1
For j As Integer = 0 To dataGridView1.Columns.Count - 1
worksheet.Cells(i + 2, j + 1) = dataGridView1.Rows(i).Cells(j).Value.ToString()
Next
'worksheet.Cells(i + 2, 1).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green)
Next
' For 1st cell i.e. A
Dim startRow As String = "A" & 2 ' From 1st row
Dim endRow As String = "A" & dataGridView1.Rows.Count ' To last row
worksheet.Range(startRow, endRow).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green)
workbook.SaveCopyAs(path)
workbook.Saved = True
Catch ex As Exception
Finally
workbook.Close()
app.Quit()
End Try
End Sub
Out put will be same as in my previous reply.