簡體   English   中英

導出到asp.net Web應用程序中的帶有選項卡(多張圖紙)的Excel

[英]Export to Excel with Tabs (Multiple Sheets) in to asp.net web app

我有一個現有的Windows應用程序,該應用程序用於將SQL數據導出為Excel格式,並且具有類別組,即標簽(工作表)。

問題:是否可以將此代碼轉換為Web表單,例如.cshtml剃刀頁面? 另外,我不希望代碼創建Excel文件。 我在App_Data文件夾下已經有一個現有文件,它將用作模板。

因此,如果有人想到使用相同的代碼,而只是生成一種新的Web方法而無需創建Excel文件,而只需為用戶創建模板文件並提供“導出”以供用戶下載。

這是代碼:

static void Main(string[] args)
{
    string conString = "Data Source="MyConnection String";
    StringBuilder query = new StringBuilder();
    query.Append("SELECT ProductPricing.ProductCategory");
    query.Append(",[ItemNo] as Item_No, [reqNumbers] as Request_No, [StockCodes] ");
    query.Append(",[Suppliers], [StockDesciption] as Stock_Description, [MaterialCosts] as Unit_Cost ");
    query.Append(",[MarginReq] as Margin, [TotalProdPrice] as Total_Price,[pOnHold] as On_Hold  ");          
    query.Append(",[pReplacement] as Replacement, [pCurrency] as Currency, [pDiscountinuedFlag] as Discountinued_Flag ");
    query.Append("FROM [TMS].[dbo].[ProductPricing] ");
    query.Append("WHERE ProductPricing.reqNumbers = 'RFQ / 384'");//"JOIN Categories ON Categories.CategoryID = Products.CategoryID ");
    query.Append("ORDER BY ProductPricing.ProductCategory ");

    SQL.DataTable dtProducts = new SQL.DataTable(); 

    using (SqlConnection cn = new SqlConnection(conString))
    {
        using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
        {
            da.Fill(dtProducts); 
        }
    }           

    Excel.Application oXL;
    Excel._Workbook oWB;
    Excel._Worksheet oSheet;
    //Anitialized

    oXL = new Excel.Application();
    oXL.Visible = true;

    oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
    oSheet = (Excel._Worksheet)oWB.ActiveSheet;

    try
    {
        SQL.DataTable dtCategories = dtProducts.DefaultView.ToTable(true, "ProductCategory");

        foreach (SQL.DataRow category in dtCategories.Rows)
        {
            oSheet = (Excel._Worksheet)oXL.Worksheets.Add();
            oSheet.Name = category[0].ToString().Replace(" ", "").Replace("  ", "").Replace("/", "").Replace("\\", "").Replace("*", "");

            string[] colNames = new string[dtProducts.Columns.Count];

            int col = 0;

            foreach (SQL.DataColumn dc in dtProducts.Columns)
                colNames[col++] = dc.ColumnName;

            char lastColumn = (char)(65 + dtProducts.Columns.Count - 1);

            oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
            oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
            oSheet.get_Range("A1", lastColumn + "1").Interior.Color =  System.Drawing.Color.SeaShell;
            oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;

            SQL.DataRow[] dr = dtProducts.Select(string.Format("ProductCategory='{0}'", category[0].ToString()));

            string[,] rowData = new string[dr.Count<SQL.DataRow>(), dtProducts.Columns.Count];

            int rowCnt = 0;
            int redRows = 2;
            foreach (SQL.DataRow row in dr)
            {
                for (col = 0; col < dtProducts.Columns.Count; col++)
                {
                    rowData[rowCnt, col] = row[col].ToString();
                }

                if (int.Parse(row["Item_No"].ToString()) < int.Parse(row["Margin"].ToString()))
                {
                    Range range = oSheet.get_Range("A" + redRows.ToString(), "M" + redRows.ToString());
                    range.Cells.Interior.Color = System.Drawing.Color.White;
                }
                redRows++;
                rowCnt++;
                //Gather the filter

            }
            if (rowCnt == 1)
            {
                rowCnt = 2;
            }
            oSheet.get_Range("A2", lastColumn + rowCnt.ToString()).Value2 = rowData;
        }   

        oXL.Visible = true;
        oXL.UserControl = true;

        //oSheet = (Excel._Worksheet)oXL.Worksheets.Delete.;

        oWB.SaveAs("ClientPricing.xlsx",
            AccessMode: Excel.XlSaveAsAccessMode.xlShared);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);  
    }
    finally
    {   
        Marshal.ReleaseComObject(oWB);
    }
}

只需使用CloseMXL.Excel庫。 這也很容易而且非常快。 我希望根據ASP ASP片段Rahul S示例創建 ,希望對其他人也有幫助!

private DataTable getAllList()
        {
            string constr = ConfigurationManager.ConnectionStrings["RConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT EmpId, gender, EmpName, pOnHold FROM Employee  WHERE EmpId= '"+ AnyVariable + "' ORDER BY EmpName"))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                        dt.Columns[0].ColumnName = "Employee Id";
                        dt.Columns[1].ColumnName = "Gender";
                        dt.Columns[2].ColumnName = "Employee Name";
                        dt.Columns[3].ColumnName = "On Hold";

                        return dt;
                    }
                }
            }
        }

然后是另一種獲取數據集的方法

public DataSet getDataSetExportToExcel()
        {
            DataSet ds = new DataSet();
            DataTable dtEmp = new DataTable("CLOT List");
            dtEmp = getAllList();
             ds.Tables.Add(dtEmp);
             ds.Tables[0].TableName = "Employee"; //If you which to use Mutliple Tabs
             return ds;
          }

現在您點擊事件

protected void btn_Export_Click(object sender, EventArgs e)
        {
            DataSet ds = getDataSetExportToExcel();

            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(ds);
                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                wb.Style.Font.Bold = true;

                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=EmployeeonHoldList.xlsx");

                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);

                    Response.Flush();
                    Response.End();
                }
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM