使用选项卡(多个表格)导出到Excel到asp.net Web应用程序

时间:2018-06-05 13:56:12

标签: c# asp.net excel razor export-to-excel

我有一个现有的Windows应用程序,用于将SQL数据导出为Excel格式,并且它的类别组是制表符(工作表)。

问题:是否可以将此代码转换为.cshtml razor页面等网页表单? 另外,我不希望代码创建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);
    }
}

1 个答案:

答案 0 :(得分:0)

  

只需使用CloseMXL.Excel库。这很简单,也很快   太。建立在ASP ASP SnippetsRahul S example之下我希望这对其他人也有帮助!

<强>类

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

现在按下Click Click

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