使用C#在Excel文件中创建报告Excel保留格式

时间:2019-03-12 17:15:11

标签: c# excel ado.net report interop

我有一个像this这样的excel文件

我正在使用以下代码:

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            string _excel_file = Path.Combine(Environment.CurrentDirectory, "rpts\\hdbh.xlsx");
            Workbook workbook = excel.Workbooks.Open(_excel_file);//, ReadOnly: false, Editable: true
            Worksheet worksheet = workbook.Worksheets.Item[1] as Worksheet;
            if (worksheet == null)
                return;

            Microsoft.Office.Interop.Excel.Range searchedRange = excel.get_Range("A3", "D3"); //XFD1048576
            foreach (DataColumn col in XuLyData._dvCt.ToTable().Columns)
            {
                Microsoft.Office.Interop.Excel.Range currentFind = searchedRange.Find("#" + col.ColumnName);
                if (currentFind != null)
                {
                    int i = 0;
                    foreach (DataRowView drv in XuLyData._dvCt)
                    {
                        worksheet.Cells[currentFind.Row + i, currentFind.Column] = drv[col.ColumnName] == DBNull.Value ? string.Empty : drv[col.ColumnName].ToString();
                        i = i + 1;
                    }
                }
            }

            excel.Application.ActiveWorkbook.Save();
            excel.Application.Quit();
            excel.Quit();

但是excel文件出来的样子像this。第2行没有第1行那样的格式。

0 个答案:

没有答案