簡體   English   中英

如何將具有 19 列的數據表中的四列導出到 C# 中的 Excel 文件中?

[英]How to export four columns from a datatable which has 19 columns into an Excel file in C#?

有一個數據表,它有 19 列和近 55 行。 我想創建一個 Excel 文件,其中僅包含其中 4 個列(“人名”、“郵寄地址”、“國家/地區-郵編”)和原始數據表中的所有數據。

注意:在原始數據表中,列country,state和zip是分開的,列的名稱是“Column12”,“Column13”,“Column14”。

我總是使用它來創建 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 文件中輕松編寫數據表

謝謝大家幫助我。 我得到了我的答案。 根據建議,我首先將 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, "董事會成員姓名", "當前地址", "永久郵寄地址", "城市-州-郵編");

現在我可以使用數據表(dt)創建 excel 文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM