首页 文章

如何将excel列添加到工作表

提问于
浏览
0

是否有人知道如何将新列插入到现有工作表中 .

我现在的解决方案是通过复制现有excel中的所有列来创建新的excel文件,然后在数据表中添加新的col,然后将其导出以创建新的excel . 这种方法有点单调乏味,只是将新列添加到现有的excel中是我看到的最佳方法 .

这是我创建新excel文件的功能

public static void ExportToExcel(DataTable tbl)
    {
        try
        {
            string dateNow = String.Format("{0:MM_dd_yyyy HH_mm_ss}", DateTime.Now);
            string excelFilePath = "C:\\The_Excel_File\\Result_" + dateNow;


            if (tbl == null || tbl.Columns.Count == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            var excelApp = new Microsoft.Office.Interop.Excel.Application();
            excelApp.Workbooks.Add();

            // single worksheet
            Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;

            // column headings
            for (var i = 0; i < tbl.Columns.Count; i++)
            {
                workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
            }

            // rows
            for (var i = 0; i < tbl.Rows.Count; i++)
            {
                // to do: format datetime values before printing
                for (var j = 0; j < tbl.Columns.Count; j++)
                {
                    workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
                }
            }

            // check file path
            if (!string.IsNullOrEmpty(excelFilePath))
            {
                try
                {
                    workSheet.SaveAs(excelFilePath);
                    excelApp.Quit();
                    //MessageBox.Show("Excel file saved!");
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                                        + ex.Message);
                }
            }
            else
            { // no file path is given
                excelApp.Visible = true;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("ExportToExcel: \n" + ex.Message);
        }
    }

1 回答

  • 0

    打开现有的Excel工作表并使用工作表使用工作表获取columncount和Rowcount,如下所述,并将此值转换为rangeaddress以编写现有的Excel工作表

    Sheet.UsedRange.Columns.Count
    
    Sheet.UsedRagne.Rows.Count
    

相关问题