使用OleDbConnection导出xlsx文件

时间:2013-09-04 12:02:01

标签: c#

我正在使用下面的代码将数据导出到xlsx文件,创建的文件但是当我尝试打开文件时,我收到错误消息,excel无法打开文件,因为文件格式或文件扩展名无效

我在我的电脑上安装的excel版本是2010年

    string fileName = "Exported" + DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") + ".xlsx";
    string filePath = ConfigurationSettings.AppSettings["Export"].ToString() + fileName;

    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
    OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
    using (System.Data.OleDb.OleDbConnection objConn = new
    System.Data.OleDb.OleDbConnection(connectionString))
    using (System.Data.OleDb.OleDbCommand cmd = new
    System.Data.OleDb.OleDbCommand("", objConn))
    {
        objConn.Open();
        cmd.CommandText = "CREATE TABLE [Sheet1] (";
        String valueNames = "(";
        Boolean first = true;
        foreach (DataColumn dc in dsDebitOrder.BAR_DEBIT_ORDER.Columns)
        {
            if (!first)
            {
                cmd.CommandText += ",\r\n";
                valueNames += ", ";
            }
            cmd.CommandText += (dc.ColumnName == "REASON" ? "[" + dc.ColumnName + "] NOTE" : "[" + dc.ColumnName + "] NVARCHAR(100)");
            valueNames += " [" + dc.ColumnName + "]";
            first = false;
        }
        cmd.CommandText += ")";
        valueNames += ")";
        cmd.ExecuteNonQuery();
        char[] trim = { '\'', '"' };
        foreach (DataRow dr in dsDebitOrder.BAR_DEBIT_ORDER.Rows)
        {
            String values = "(";
            first = true;
            foreach (DataColumn dc in dsDebitOrder.BAR_DEBIT_ORDER.Columns)
            {
                if (!first)
                    values += ", ";
                values += "\"" + (Regex.Replace(dr[dc].ToString().Trim(trim), "\"", "") == "-1" ? string.Empty : Regex.Replace(dr[dc].ToString().Trim(trim), "\"", "")) + "\"";
                first = false;
            }
            values += ")";
            cmd.CommandText = "INSERT INTO [Sheet1] " +
            valueNames + " VALUES " + values;
            cmd.ExecuteNonQuery();
        }
        if (con != null)
        {
            con.Close();
            con.Dispose();
        }
    }
    System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
    String sFileLength = fi.Length.ToString();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Current.Response.Charset = "";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    HttpContext.Current.Response.AddHeader("Content-Length", sFileLength);
    HttpContext.Current.Response.TransmitFile(filePath);
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.Close();

0 个答案:

没有答案