如何对所有列数据运行sql查询并将结果导出到csv -in c#

时间:2016-11-17 14:01:01

标签: c# sql .net csv

我在访问数据库上进行了sql查询。在datagridview2中,我在第一列中看到第二列中的istalled程序,该程序安装了多少台计算机。

col1   col2
xxxx    1
yyyy    2
zzzz    3

OleDbCommand command2 = new OleDbCommand();
            command2.Connection = connection;
            string query = "SELECT Item_1, count(Item_1)   FROM  (SELECT  Item_1 FROM Audit_data where Category_ID = 500)    group by Item_1 having (count(*)>0)   ";

                   command2.CommandText = query;

            OleDbDataAdapter da1 = new OleDbDataAdapter(command2);

            da1.Fill(dt2);
            dataGridView2.DataSource = dt2;
            dataGridView2.AutoResizeColumns();

datagridview3仅包含在datagridview2上更改选择时安装程序的计算机名称:

 string selcell = Convert.ToString(dataGridView2.CurrentCell.Value);



            OleDbCommand command3 = new OleDbCommand();
            command3.Connection = connection;
            string query = "select distinct Fully_Qualified_Domain_Name from Audit_Data, Computer_master where Item_1= '"+selcell+"'    and category_id=500      and Audit_Data.computer_id = Computer_master.computer_id     ";     

            command3.CommandText = query;

            OleDbDataAdapter da3 = new OleDbDataAdapter(command3);

            da3.Fill(dt3);
            dataGridView3.DataSource = dt3;
            dataGridView3.AutoResizeColumns();

我想运行这些查询以获取所有已安装计算机名称的软件。我不知道如何对col 1上的所有数据运行查询,并将其导出到csv,就像这样。

xxxx; 1; qwer_pc
yyyy; 2; asdf_pc;
         qwer_pc
zzzz; 3; asdf_pc;
         qwer_pc;
         yxcv_pc

有人可以帮忙解决这个问题吗? 或者我可以以某种方式组合这两个查询?

1 个答案:

答案 0 :(得分:0)

解决方案比我想象的更容易:

SELECT distinct Item_1,Fully_Qualified_Domain_Name FROM Audit_data,Computer_master where Category_ID = 500      and    Audit_data.computer_id = Computer_master.Computer_id          

CSV导出如下:

     string csv = string.Empty;

//Add the Header row for CSV file.
foreach (DataGridViewColumn column in dataGridView4.Columns)
{
    csv += column.HeaderText + ',';
}

//Add new line.
csv += "\r\n";

//Adding the Rows
foreach (DataGridViewRow row in dataGridView4.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        //Add the Data rows.
        csv += cell.Value.ToString().Replace(",", ";") + ',';
    }

    //Add new line.
    csv += "\r\n";
}

//Exporting to CSV.
string folderPath = txt_csv_exp_path.Text;
File.WriteAllText(folderPath +txt_exp_file_name.Text +" .csv", csv);

MessageBox.Show("CSV file saved.");