1

我在为我的工作表 2 设置标题时遇到了一些问题

这是我的代码:

            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;

            }

我应该为工作表 2 的新标题创建新的 Excel 应用程序吗?但我没有任何意义。有人可以帮我吗?谢谢你们...

4

1 回答 1

1

您可以写入任何您想要的单元格,包括标题单元格。只需选择要在其中插入标题的工作表。

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";
于 2012-10-05T09:35:16.377 回答