在Excel中颜色特定的行C#

我正在创build一份我日常报告的优秀工作书。 我想让标题部分颜色变成黄色。 所有发布的链接要么打开工作簿的链接,要么不是特定于probelm的链接。 我在这里张贴我的代码,请build议如何使第6行黄色。

string workBookName; // creating Excel Application Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); // creating new WorkBook within Excel application Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); // creating new Excelsheet in workbook Microsoft.Office.Interop.Excel._Worksheet worksheet = null; // see the excel sheet behind the program app.Visible = true; // get the reference of first sheet. By default its name is Sheet1. // store its reference to worksheet worksheet = workbook.Sheets["Sheet1"]; worksheet = workbook.ActiveSheet; // changing the name of active sheet workBookName = DateTime.Now.ToString("ddMMMyyyy-HHmmss"); worksheet.Name = workBookName; worksheet.Cells[1, 1] = "Logistics"; worksheet.Cells[2, 1] = "Tracking Number"; worksheet.Cells[4, 2] = "Date - "; worksheet.Cells[4, 3] = dateTimePicker1.Value.ToString("dd/MMM/yyyy"); // storing header part in Excel for (int i = 1; i < dataGridView1.Columns.Count + 1; i++) { worksheet.Cells[6, i] = dataGridView1.Columns[i - 1].HeaderText; // worksheet.get_Range(worksheet.Cells[6, i]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green); } // storing Each row and column value to excel sheet for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { for (int j = 0; j < dataGridView1.Columns.Count; j++) { //if (!string.IsNullOrWhiteSpace(dataGridView1.Rows[i].Cells[j].Value)) { worksheet.Cells[i + 8, j + 1] = dataGridView1.Rows[i].Cells[j].Value; } } } // save the application workbook.SaveAs("Tracking Number Report " + workBookName + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // Exit from the application app.Quit(); 

我想要第6行,这是在我的情况下的头部被着色。

如果你运行这个代码,你将最终得到一个仍在运行的Excel实例,因为你还没有使用.ReleaseComObject调用在互操作中释放资源 – 关于这个的更多信息

我更喜欢使用Open XML库之一,如EPPlus这种types的东西。 它使事情变得简单许多,并且使得行变得容易。

尝试这样的事情:

 using (var excel = new ExcelPackage()) { var workBookName = DateTime.Now.ToString("ddMMMyyyy-HHmmss"); var worksheet = excel.Workbook.Worksheets.Add(workBookName); worksheet.Cells[1, 1].Value = "Logistics"; worksheet.Cells[2, 1].Value = "Tracking Number"; worksheet.Cells[4, 2].Value = "Date - "; worksheet.Cells[4, 3].Value = dateTimePicker1.Value.ToString("dd/MMM/yyyy"); for (int i = 1; i < dataGridView1.Columns.Count + 1; i++) { worksheet.Cells[6, i].Value = dataGridView1.Columns[i - 1].HeaderText; } worksheet.Cells["6:6"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; worksheet.Cells["6:6"].Style.Fill.BackgroundColor.SetColor(Color.Yellow); // //..etc // excel.SaveAs(new FileInfo("Tracking Number Report " + workBookName + ".xlsx")); }