【问题标题】:How to add excel column to worksheet如何将excel列添加到工作表
【发布时间】:2017-03-14 18:49:59
【问题描述】:

有谁知道如何在现有工作表中插入新列。

我目前的解决方案是通过复制现有 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);
        }
    }

【问题讨论】:

    标签: c# excel oledb


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 2018-07-03
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多