问题
I habe some problems with setting the header for my worksheet 2
Here is my code:
Excel.Application xlApp1 = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet1 = new Excel.Worksheet();
Excel.Worksheet xlWorkSheet2 = new Excel.Worksheet();
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp1.Workbooks.Add(misValue);
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); // Sheet1
xlWorkSheet1.Name = "XX";
xlWorkSheet2 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2); // Sheet2
xlWorkSheet2.Name = "YY";
Excel.Range headerRange = xlApp1.get_Range("A1", "V1");
headerRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
xlApp1.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
Should I make new Excel Application for new header for Worksheet 2? but i doesn't make any sense. Can anyone help me with it? thanks you guys...
回答1:
You can write to any cell you want, including the header cells. Just choose the worksheet in which you want to insert the header.
Excel.Range headerRange = xlWorkSheet1.get_Range("A1", "V1");
headerRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange.Value = "Header text 1";
headerRange = xlWorkSheet2.get_Range("A1", "V1");
headerRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange.Value = "Header text 2";
来源:https://stackoverflow.com/questions/12742824/set-header-in-excel-for-worksheet-2