Set header in Excel for worksheet 2

偶尔善良 提交于 2019-12-11 04:56:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!