如何使用 Microsoft.Office.Interop dll 在 c# 控制台应用程序中将数据集导出到 excel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8818404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to export dataset to excel in c# console application using Microsoft.Office.Interop dll
提问by Kathirvel
How do I export data from my C# console application to Excel using Microsoft.Office.Interop dll?
如何使用 Microsoft.Office.Interop dll 将数据从 C# 控制台应用程序导出到 Excel?
回答by sonu thomas
You can get many Excel tutorials for c sharp available on internet
您可以在互联网上获得许多有关 c 锐利的 Excel 教程
Refer to this link http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
请参阅此链接http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
Update
更新
You go to this link for your solution with dataset
您转到此链接以获取包含数据集的解决方案
Hope this may help you
希望这可以帮助你
回答by NDraskovic
Add a using statement like this:
添加一个 using 语句,如下所示:
using Excel = Microsoft.Office.Interop.Excel;
Then define a variable that will enable you to work with Excel documents and workbooks:
然后定义一个变量,使您能够处理 Excel 文档和工作簿:
Excel.Application xlApp = new Excel.Application();
Create a function that will write from your DataSet into an Excel document (This is from one of my Windows applications button_click function, but I think you will be able to make the necessary adjustments):
创建一个函数,该函数将从您的数据集写入 Excel 文档(这是来自我的 Windows 应用程序之一的 button_click 函数,但我认为您将能够进行必要的调整):
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow red = dataGridView1.Rows[i];
for (int j = 0; j < red.Cells.Count-2; j++)
{
if (j != 0)
{
xlApp.Cells[i + 1, j + 1] = "'" + Convert.ToString(red.Cells[j].Value);
}
else
{
xlApp.Cells[i + 1, j + 1] = Convert.ToString(red.Cells[j].Value);
}
}
}
xlApp.AutoCorrect.ReplaceText = false;
saveFileDialog1.DefaultExt = ".xls";
saveFileDialog1.FileName = textBox2.Text;
saveFileDialog1.InitialDirectory = "Desktop";
saveFileDialog1.ShowDialog();
try
{
xlApp.ActiveWorkbook.SaveCopyAs(FileName);
}
catch
{
MessageBox.Show("Warning");
}
ImeDatoteke = "";
xlApp.Quit();
As you see, I use DataGridView to display the data that I want to write into the Excel file, but since DataGridView uses DataSets I dont think you will have to much problems to adjust this code
如您所见,我使用 DataGridView 来显示我想写入 Excel 文件的数据,但由于 DataGridView 使用 DataSets,我认为调整此代码不会有太多问题

