简体   繁体   中英

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

I have an Excel file template, and I need to extract the data from a SQL Server database to this Excel file using C# as same as the template file.

The problem is that I need to add another column using C# to the Excel file, to make this extracted file look like the template file.

So I will not extract the Excel file's data from my web-form application directly. I need to add some additional columns first.

Convert SQL to CSV while writing SQL result add your custom column data as well. CSV will open in excel by default.

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();
        }
    }

You can covert csv to 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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