为每个单元格添加边框后,当SaveAs一个Excel工作表时,应用程序崩溃

问题描述

我试图在Excel工作表中添加边框,我使用C#填充了datagridview表中的信息。添加代码后:


            Excel.Range tRange = worksheet.UsedRange;
            tRange.Borders.Linestyle = Excel.XlLinestyle.xlContinuous;
            tRange.Borders.Weight = Excel.XlBorderWeight.xlThin;

此处:

private void btnExportToExcel_Click(object sender,EventArgs e)
        {
            Excel._Application app = new Excel.Application();
            Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            Excel._Worksheet worksheet = null;

            worksheet = workbook.Sheets["Sheet1"];
            worksheet.Name = "Frames";
            worksheet.Columns[2].NumberFormat = "@"; //format the product_id column for displaying the whole number

            for (int i = 1; i < dgwFrames.Columns.Count +1; i++)
            {
                worksheet.Cells[1,i] = dgwFrames.Columns[i - 1].HeaderText;
            }
            for (int i = 0; i < dgwFrames.Rows.Count; i++)
            {
                for(int j = 0; j< dgwFrames.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2,j + 1] = dgwFrames.Rows[i].Cells[j].Value.ToString();
                }
            }
            var saveFileDialog = new SaveFileDialog();
            DateTime today = DateTime.Today;
            saveFileDialog.FileName = $"FramesList_{today.Date.Day}-{today.Date.Month}-{today.Date.Year}";
            saveFileDialog.DefaultExt = ".xlsx";

            Excel.Range tRange = worksheet.UsedRange;
            tRange.Borders.Linestyle = Excel.XlLinestyle.xlContinuous;
            tRange.Borders.Weight = Excel.XlBorderWeight.xlThin;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                workbook.SaveAs(saveFileDialog.FileName,Type.Missing,Excel.XlSaveAsAccessMode.xlExclusive,Type.Missing);
            }
            app.Quit();
        }

它开始给我错误

System.Runtime.InteropServices.COMException:'来自HRESULT的异常:0x800A03EC'

SaveAs方法的顶部。

其原因是什么,我该如何解决?预先感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)