【问题标题】:How to export four columns from a datatable which has 19 columns into an Excel file in C#?如何将具有 19 列的数据表中的四列导出到 C# 中的 Excel 文件中?
【发布时间】:2020-06-07 06:31:42
【问题描述】:

有一个数据表,它有 19 列和近 55 行。我想创建一个 Excel 文件,其中仅包含其中 4 个列(“人名”、“邮寄地址”、“国家/地区-邮编”)和原始数据表中的所有数据。

注意:原始数据表中的country、state和zip列是分开的,列的名称是“Column12”、“Column13”、“Column14”。

【问题讨论】:

  • 你自己尝试过什么来解决这个问题? (除了发帖到 SO)我想说的是,SO 有很多例子可以开始看:stackoverflow.com/search?q=csv+to+excel+c%23+
  • 非常感谢您的回答。我自己尝试过,但我可以从原始数据表中导出所有数据(列),我只想从原始数据表中导出 4 列。我看到了那个链接,但没有什么与我的问题不符。
  • 想想你怎么能解决这个问题......你可以创建这个数据表的副本,其中只有你需要的四列。然后您的情况与链接中找到的(某些)示例相匹配。

标签: c# excel


【解决方案1】:

我总是用这个来创建excel文件(当然我想你已经安装了interops Excel)

写入新 excel 的示例:

using Excel = Microsoft.Office.Interop.Excel;
//First we have to initialize the Excel application Object.
Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

//Before creating new Excel Workbook, you should check whether Excel is installed in your system.
if (excelApp == null)
{
    MessageBox.Show("Excel is not properly installed!!");
    return;
}

Excel.Workbook excelWorkbook = excelApp.Workbooks.Add();
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets.Add();

//fill 4 rows of col 1
excelWorksheet.Cells[1, 1] = "NameOfCol1";
excelWorksheet.Cells[2, 1] = "Value1";
excelWorksheet.Cells[3, 1] = "Value2";
excelWorksheet.Cells[4, 1] = "Value3";

excelApp.ActiveWorkbook.SaveAs(@"C:\abc.xls", Excel.XlFileFormat.xlWorkbookNormal);

excelWorkbook.Close();
excelApp.Quit();

你当然会适应你的问题。因此,您可以轻松地将数据表写入 excel 文件中

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

谢谢大家帮助我。我得到了我的答案。根据建议,我首先将 3 列合并为一个列原始数据表(City + State + Zip)。然后我从原始数据表中提取 3 列。我的代码是:

//将3列组合成原始数据表(dt)并命名为“City-State-Zip”。

dt.Columns.Add("City-State-Zip", typeof(string), "Column12+','+Column13+','+Column14").ToString();

//从原始数据表(dt)中提取三列到dt2中

dt2 = dt.DefaultView.ToTable(false, "董事会成员姓名", "当前地址", "永久邮寄地址", "City-State-Zip");

现在我可以使用数据表 (dt) 创建 excel 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2021-02-18
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多