我正在创建一份日常报告的excel工作簿。我希望标题部分变为黄色。发布的所有链接都需要要打开的工作簿链接或不是特定于probelm的链接。我在这里发布我的代码,请建议如何使第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行,在我的情况下,标题部分是彩色的。
答案 0 :(得分:0)
如果您运行此代码,最终仍会运行Excel实例,因为您尚未使用.ReleaseComObject
调用在互操作中释放资源 - 有关此here的更多信息
我更喜欢使用其中一个Open XML库,例如EPPlus来处理这类事情。它使事情变得更简单,并且可以很容易地为一行着色。
尝试这样的事情:
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"));
}