SQL Server:查询导出为CSV

时间:2016-04-06 09:28:59

标签: c# sql sql-server csv

我想将此查询的结果导出到CSV文件,但是当我把它放在服务器上时它不起作用。

当我在本地运行时,它很好,但是一旦我将它上传到服务器,它就不会做任何事情并且崩溃应用程序。有人能帮帮我吗?

protected void btnExport_Click(object sender, EventArgs e)
{
    string sCon = ConfigurationManager.ConnectionStrings["PayrollPlusConnectionString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(sCon))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT ManualAdjustments.PTLName, ManualAdjustments.PTLStaffID, ManualAdjustments.CampusOccurred, ManualAdjustments.DeptOccurred, ManualAdjustments.DateOccurred, ManualAdjustments.CourseDetails, ManualAdjustments.Duration, ManualAdjustments.ValueOfDuration, ManualAdjustments.Grade, ManualAdjustments.CostCentre, ManualAdjustments.Comment, ManualAdjustments.Reason, ManualAdjustments.RatePerHour, ManualAdjustments.Pay, ManualAdjustments.PayPeriod FROM ManualAdjustments INNER JOIN PayrollPeriod ON ManualAdjustments.PayPeriod = PayrollPeriod.PayrollPeriod ORDER BY ManualAdjustments.PTLName"))
        {
                SqlDataAdapter sda = new SqlDataAdapter();

                try
                {
                    cmd.Connection = con;
                    con.Open();
                    sda.SelectCommand = cmd;

                    DataTable dt = new DataTable();
                    sda.Fill(dt);

                    if (dt.Rows.Count > 0)
                    {
                        string path = Server.MapPath("exportedfiles\\");

                        if (!Directory.Exists(path))   // CHECK IF THE FOLDER EXISTS. IF NOT, CREATE A NEW FOLDER.
                        {
                            Directory.CreateDirectory(path);
                        }

                        File.Delete(path + "ManualAdjustments.xlsx"); // DELETE THE FILE BEFORE CREATING A NEW ONE.

                        // ADD A WORKBOOK USING THE EXCEL APPLICATION.
                        Excel.Application xlAppToExport = new Excel.Application();
                        xlAppToExport.Workbooks.Add("");

                        // ADD A WORKSHEET.
                        Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet);
                        xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Sheet1"];

                        // ROW ID FROM WHERE THE DATA STARTS SHOWING.
                        int iRowCnt = 2;

                        //// SHOW THE HEADER.
                        //xlWorkSheetToExport.Cells[1, 1] = "Manual Adjustments";

                        //Excel.Range range = xlWorkSheetToExport.Cells[1, 1] as Excel.Range;
                        //range.EntireRow.Font.Name = "Calibri";
                        //range.EntireRow.Font.Bold = true;
                        //range.EntireRow.Font.Size = 20;

                        //xlWorkSheetToExport.Range["A1:D1"].MergeCells = true;       // MERGE CELLS OF THE HEADER.

                        // SHOW COLUMNS ON THE TOP.
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 1] = "PTL Name";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 2] = "PTL Staff ID";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 3] = "Campus";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 4] = "Department";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 5] = "Date";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 6] = "Course Details";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 7] = "Duration";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 8] = "Value of Duration";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 9] = "Grade";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 10] = "Cost Centre";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 11] = "Reason";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 12] = "Comment";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 13] = "Rate Per Hour";
                        xlWorkSheetToExport.Cells[iRowCnt - 1, 14] = "Pay";


                        int i;
                        for (i = 0; i <= dt.Rows.Count - 1; i++)
                        {
                            xlWorkSheetToExport.Cells[iRowCnt, 1] = dt.Rows[i].Field<string>("PTLName");
                            xlWorkSheetToExport.Cells[iRowCnt, 2] = dt.Rows[i].Field<string>("PTLStaffID");
                            xlWorkSheetToExport.Cells[iRowCnt, 3] = dt.Rows[i].Field<string>("CampusOccurred");
                            xlWorkSheetToExport.Cells[iRowCnt, 4] = dt.Rows[i].Field<string>("DeptOccurred");
                            xlWorkSheetToExport.Cells[iRowCnt, 5] = dt.Rows[i].Field<string>("DateOccurred");
                            xlWorkSheetToExport.Cells[iRowCnt, 6] = dt.Rows[i].Field<string>("CourseDetails");
                            xlWorkSheetToExport.Cells[iRowCnt, 7] = dt.Rows[i].Field<string>("Duration");
                            xlWorkSheetToExport.Cells[iRowCnt, 8] = dt.Rows[i].Field<decimal>("ValueOfDuration");
                            xlWorkSheetToExport.Cells[iRowCnt, 9] = dt.Rows[i].Field<int>("Grade");
                            xlWorkSheetToExport.Cells[iRowCnt, 10] = dt.Rows[i].Field<string>("CostCentre");
                            xlWorkSheetToExport.Cells[iRowCnt, 11] = dt.Rows[i].Field<string>("Reason");
                            xlWorkSheetToExport.Cells[iRowCnt, 12] = dt.Rows[i].Field<string>("Comment");
                            xlWorkSheetToExport.Cells[iRowCnt, 13] = dt.Rows[i].Field<decimal>("RatePerHour");
                            xlWorkSheetToExport.Cells[iRowCnt, 14] = dt.Rows[i].Field<decimal>("Pay");

                            iRowCnt = iRowCnt + 1;
                        }

                        // FINALLY, FORMAT THE EXCEL SHEET USING EXCEL'S AUTOFORMAT FUNCTION.
                        //Excel.Range range1 = xlAppToExport.ActiveCell.Worksheet.Cells[4, 1] as Excel.Range;
                        //range1.AutoFormat(ExcelAutoFormat.xlRangeAutoFormatList3);

                        // SAVE THE FILE IN A FOLDER.
                        xlWorkSheetToExport.SaveAs(path + "ManualAdjustments.xlsx");

                        // CLEAR.
                        xlAppToExport.Workbooks.Close();
                        xlAppToExport.Quit();
                        xlAppToExport = null;
                        xlWorkSheetToExport = null;

                    }
                }
                catch (Exception ex)
                {
                    lblConfirm.Text = ex.Message.ToString();
                    lblConfirm.Attributes.Add("style", "color:red; font: bold 14px/16px Sans-Serif,Arial");
                }
                finally
                {
                    sda.Dispose();
                    sda = null;


                    //download file

                    try
                    {
                        string sPath = Server.MapPath("exportedfiles\\");

                        Response.AppendHeader("Content-Disposition", "attachment; filename=ManualAdjustments.xlsx");
                        Response.TransmitFile(sPath + "ManualAdjustments.xlsx");
                        Response.End();
                    }
                    catch (Exception ex) { }
                }
            }
    }
}

尝试了一种不同的方法,但仍然无法正常工作,我认为这与尝试保存到PC上的本地文件有关。有没有办法解决这个问题?

protected void btnExportMA_Click(object sender,EventArgs e)         {             string strDelimiter =&#34;,&#34 ;;             string cs = ConfigurationManager.ConnectionStrings [&#34; PayrollPlusConnectionString&#34;] .ConnectionString;

        StringBuilder sb = new StringBuilder();

        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlDataAdapter da = new SqlDataAdapter("SELECT DISTINCT ManualAdjustments.PTLName, ManualAdjustments.PTLStaffID, ManualAdjustments.CampusOccurred, ManualAdjustments.DeptOccurred, ManualAdjustments.DateOccurred, ManualAdjustments.CourseDetails, ManualAdjustments.Duration, ManualAdjustments.ValueOfDuration, ManualAdjustments.Grade, ManualAdjustments.CostCentre, ManualAdjustments.Comment, ManualAdjustments.Reason, ManualAdjustments.RatePerHour, ManualAdjustments.Pay, ManualAdjustments.PayPeriod FROM ManualAdjustments INNER JOIN PayrollPeriod ON ManualAdjustments.PayPeriod = PayrollPeriod.PayrollPeriod ORDER BY ManualAdjustments.PTLName", con);
            DataSet ds = new DataSet();
            da.Fill(ds);

            ds.Tables[0].TableName = "Manual Adjustments";

            foreach (DataRow MADR in ds.Tables["Manual Adjustments"].Rows)
            {
                string PTLName = Convert.ToString(MADR["PTLName"]);
                sb.Append(PTLName.ToString() + strDelimiter);

                sb.Append(MADR["PTLStaffID"].ToString() + strDelimiter);

                sb.Append("\r\n");

                //add all other columns here (no delimiter in last column)


            }
        }

        StreamWriter file = new StreamWriter(@"H:\ManualAdjustments.txt");
        file.WriteLine(sb.ToString());
        file.Close();

    }

1 个答案:

答案 0 :(得分:0)

 using (ExcelPackage excelPack = new ExcelPackage())
            {
               // Add ExcelWorksheet  ExcelWorksheet excelWorksheet = excelPack.Workbook.Worksheets.Add("NAME");
               // formatting ExcelWorksheet here... 
                string sPath = Server.MapPath("exportedfiles\\");
                string FileName =sPath + "ManualAdjustments.xlsx";
                FileInfo fiCustom = new FileInfo(FileName);
                excelPack.SaveAs(fiCustom);
                System.Diagnostics.Process.Start(FileName, "cmd");
            }

试试这个......