how to export dataset to excel in c# console appli

2019-04-17 01:38发布

How do I export data from my C# console application to Excel using Microsoft.Office.Interop dll?

标签: c# ms-office
2条回答
男人必须洒脱
2楼-- · 2019-04-17 02:32

You can get many Excel tutorials for c sharp available on internet

Refer to this link 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

查看更多
放我归山
3楼-- · 2019-04-17 02:35

Add a using statement like this:

using Excel = Microsoft.Office.Interop.Excel;

Then define a variable that will enable you to work with Excel documents and workbooks:

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):

        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

查看更多
登录 后发表回答