繁体   English   中英

有没有一种方法可以使用C#从ado.net查询中提取Excel文件并向其中添加自定义列

[英]Is there a way for extracting an Excel file from an ado.net query and adding custom columns to it using c#

我有一个Excel文件模板,并且需要使用与模板文件相同的C#将SQL Server数据库中的数据提取到此Excel文件中。

问题是我需要使用C#将另一列添加到Excel文件中,以使提取的文件看起来像模板文件。

因此,我不会直接从Web窗体应用程序中提取Excel文件的数据。 我需要先添加一些其他列。

在编写SQL结果时将SQL转换为CSV以及添加自定义列数据。 CSV默认会在excel中打开。

private void SQLToCSV(string query, string Filename)
    {

        SqlConnection conn = new SqlConnection(connection);
        conn.Open();
        SqlCommand cmd = new SqlCommand(query, conn);
        SqlDataReader result = cmd.ExecuteReader();

        using (System.IO.StreamWriter fs = new System.IO.StreamWriter(Filename))
        {
            // Loop through the fields and add headers
            for (int i = 0; i < result.FieldCount; i++)
            {
                string colval = result.GetColumnName(i);
                if (colval.Contains(","))
                    colval = "\"" + colval + "\"";

                fs.Write(colval + ",");
            }

    //CONCATENATE THE COLUMNS YOU WANT TO ADD IN RESULT HERE

            fs.WriteLine();

           // Loop through the rows and output the data
            while (result.Read())
            {
                for (int i = 0; i < result.FieldCount; i++)
                {
                    string value = result[i].ToString();
                    if (value.Contains(","))
                        value = "\"" + value + "\"";

                    fs.Write(value + ",");
                }
                fs.WriteLine();
            }

            fs.Close();
        }
    }

您可以将CSV转换为Excel

using Excel = Microsoft.Office.Interop.Excel;

private void Convert_CSV_To_Excel()
{

    // Rename .csv To .xls
    System.IO.File.Move(@"d:\Test.csv", @"d:\Test.csv.xls");

    var _app = new Excel.Application();
    var _workbooks = _app.Workbooks;

    _workbooks.OpenText("Test.csv.xls",
                             DataType: Excel.XlTextParsingType.xlDelimited,
                             TextQualifier: Excel.XlTextQualifier.xlTextQualifierNone,
                             ConsecutiveDelimiter: true,
                             Semicolon: true);

    // Convert To Excle 97 / 2003
    _workbooks[1].SaveAs("NewTest.xls", Excel.XlFileFormat.xlExcel5);

    _workbooks.Close();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM