如何使用.net删除导出的Excel中的表格式

时间:2016-06-28 02:00:26

标签: c# .net excel

目前我正在使用closedxml.excel创建包含多个Excel工作表的excel工作簿,但是它也有助于同时在每个Excel工作表中创建“表格格式”功能,这禁止我复制或移动多个Excel工作表同时使用另一个新的excel工作簿。

为了将多个Excel工作表一次复制并移动到另一个Excel工作表,我必须在数据表中创建没有任何格式的excel工作簿。

protected void Button5_Click(object sender, EventArgs e){

    type = "none";
    Boolean checks = true;
    String errormsg = "";
    int fromYear = 1;
    int fromMonth = 1;
    int toYear = 1;
    int toMonth = 1;
    int toDay = 1;
    DateTime fromdate = new DateTime(2015, 1, 1);
    DateTime todate = new DateTime(2015, 1, 1);

    ArrayList accTemp = new ArrayList();
    //check for selected account
    if (cbacc1.Checked == true)
    {
        accTemp.Add("I");
    }
    if (cbacc2.Checked == true)
    {
        accTemp.Add("II");
    }
    if (cbacc3.Checked == true)
    {
        accTemp.Add("III");
    }
    if (cbacc4.Checked == true)
    {
        accTemp.Add("IV");
    }
    acc = accTemp;
    if (accTemp.Count == 0)
    {
        checks = false;
        errormsg = "Please select an account";
        ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('" + errormsg + "');", true);
    }
    try
    {
        //Retrieve From date from text and store as datetime
        fromYear = Convert.ToInt32(fromDateyear.Text);
        fromMonth = Convert.ToInt32(fromDatemonth.Text);
        fromdate = new DateTime(fromYear, fromMonth, 1);

        //Retrieve To date from text and store as datetime
        toYear = Convert.ToInt32(toDateyear.Text);
        toMonth = Convert.ToInt32(toDatemonth.Text);
        todate = new DateTime(toYear, toMonth, DateTime.DaysInMonth(toYear, toMonth));

    }
    catch (ArgumentOutOfRangeException es)
    {
        checks = false;
        errormsg = "Please enter correct date";
        ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('" + errormsg + "');", true);
    }
    catch (FormatException es)
    {
        checks = false;
        errormsg = "Please enter Date";
        ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('" + errormsg + "');", true);
    }

    int monthdiff = 0;



    //Get number of month
    if (toYear == fromYear)
    {
        monthdiff = toMonth - fromMonth;
        if (toMonth == 2)
        {
            if (toDay >= 28)
            {
                monthdiff = monthdiff + 1;
            }
        }
        else if (toMonth == 1 || toMonth == 3 || toMonth == 5 || toMonth == 7 || toMonth == 8 || toMonth == 10 || toMonth == 12)
        {
            if (toDay >= 31)
            {
                monthdiff = monthdiff + 1;
            }
        }
        else if (toMonth == 4 || toMonth == 6 || toMonth == 9 || toMonth == 11)
        {
            if (toDay >= 30)
            {
                monthdiff = monthdiff + 1;
            }
        }

    }
    else if (toYear > fromYear)
    {
        monthdiff = 12 - fromMonth;
        monthdiff = monthdiff + toMonth;
        if (toYear - fromYear == 1)
        {
        }
        else if (toYear - fromYear > 1)
        {
            int yeardiff = toYear - fromYear;
            monthdiff += 12 * (yeardiff - 1);
        }
    }

    // check for valid Date
    if (fromdate.Year < 2009 || todate.Year < 2009)
    {
        checks = false;
        errormsg = "Invalid Date";
        ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('" + errormsg + "');", true);
    }
    if (fromdate.Date > todate.Date)
    {
        checks = false;
        errormsg = "From Date cannot be greater than To Date";
        ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('" + errormsg + "');", true);
    }
    int selectedCounts = CheckBoxList1.Items.Cast<ListItem>().Count(li => li.Selected);
    if (selectedCounts == 0)
    {
        checks = false;
        errormsg = "Please select factor";
        ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('" + errormsg + "');", true);
    }

    if (checks == true)
    {
        //DateArray and PreDate Array are used to store date as date format. Shall be use for tradeDate and SetlDate
        preDateArray = new DateTime[monthdiff + 1];
        DateArray = new DateTime[monthdiff + 1];
        DateTime preDA = new DateTime(fromYear, fromMonth, DateTime.DaysInMonth(fromYear, fromMonth));
        DateTime time = preDA.AddMonths(-1);
        int months = time.Month;
        int years = time.Year;
        preDateArray[0] = new DateTime(years, months, DateTime.DaysInMonth(years, months));

        for (int i = 0; i < monthdiff; i++)
        {

            DateTime times = preDA.AddMonths(i);
            int day = times.Day;
            int month = times.Month;
            int year = times.Year;
            DateTime tests = new DateTime(year, month, DateTime.DaysInMonth(year, month));
            preDateArray[i + 1] = tests;
        }
        for (int i = 0; i < monthdiff + 1; i++)
        {
            DateTime times = preDA.AddMonths(i);
            int day = times.Day;
            int month = times.Month;
            int year = times.Year;
            DateTime tests = new DateTime(year, month, DateTime.DaysInMonth(year, month));
            DateArray[i] = tests;
        }

        //DateList and PreDateList are used to store date as String format. shall be use for portfolioAsAt and UploadFrom/toDate
        DateList = new String[monthdiff + 1];
        PreDateList = new String[monthdiff + 1];
        for (int i = 0; i < DateArray.Length; i++)
        {
            DateList[i] = (DateArray[i]).ToString("yyyyMMdd");
            PreDateList[i] = (preDateArray[i]).ToString("yyyyMMdd");

        }

        if (DropDownList1.SelectedIndex != -1)
        {
            ConvertType = DropDownList1.SelectedValue;
        }

        List<Attribute_2f> result;
        //HiddenField value store the CheckBoxs values
        String cbattr = HiddenField1.Value;
        //Split the String Value in to String Array
        String[] cbattr1 = cbattr.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

        //Store as ArrayList
        ArrayList ha = new ArrayList();
        foreach (String attrc in cbattr1)
        {
            ha.Add(attrc);
        }
        result = Attribute_2f.getInfo(ha, acc, preDateArray, DateArray, PreDateList, DateList, ConvertType, "none", null);

        DataSet ds = new DataSet();
        String facc = "";
        foreach (String attrc in cbattr1)
        {
            ha.Add(attrc);
        }

        ArrayList clickfactor1 = new ArrayList();
        Attribute_2f clickfactor = new Attribute_2f();
        List<Attribute_2f> fac = null;
        int y = 0;
        int p = 0;
        //int c = 0;
        fac = Attribute_2f.getFactors(acc, DateList, ha, PreDateList, "none");
        foreach (Attribute_2f factemp in fac)
        {
            clickfactor.setFactor("'" + "'" + factemp.getFactor() + "'" + "'");
            clickfactor.setFactor2("'" + "'" + factemp.getFactor2() + "'" + "'");
            clickfactor.setFactor3("'" + "'" + factemp.getFactor3() + "'" + "'");
            clickfactor.setFactor4("'" + "'" + factemp.getFactor4() + "'" + "'");
            clickfactor1.Add(clickfactor);

            if (cbattr1.Count() == 1)
            {
                facc = factemp.getFactor().ToString();
            }
            if (cbattr1.Count() == 2)
            {
                facc = factemp.getFactor().ToString() + ", " + factemp.getFactor2().ToString();
            }
            if (cbattr1.Count() == 3)
            {
                facc = factemp.getFactor().ToString() + ", " + factemp.getFactor2().ToString() + ", " + factemp.getFactor3().ToString();
            }
            if (cbattr1.Count() == 4)
            {
                facc = factemp.getFactor().ToString() + ", " + factemp.getFactor2().ToString() + ", " + factemp.getFactor3().ToString() + ", " + factemp.getFactor4().ToString();
            }
            if (facc.Contains("ILS (Insurance Linked Security)"))
            {
                facc = facc.Replace("ILS (Insurance Linked Security)", "ILS");
            }
            if (facc.Contains("SFR (Single Family Rental)"))
            {
                facc = facc.Replace("SFR (Single Family Rental)", "SFR");
            }
            if (facc.Contains("Retail & Business Products"))
            {
                facc = facc.Replace("Retail & Business Products", "R&B Products");
            }
            if (facc.Contains("Construction & Homebuilding"))
            {
                facc = facc.Replace("Construction & Homebuilding", "Constr & Home");
            }
            if (facc.Contains("Leisure, Lodging & Entertainment"))
            {
                facc = facc.Replace("Leisure, Lodging & Entertainment", "Leisure");
            }
            if (facc.Contains("Latin America"))
            {
                facc = facc.Replace("Latin America", "LATAM");
            }
            if (facc.Contains("North America"))
            {
                facc = facc.Replace("North America", "NA");
            }
            if (facc.Contains("Middle East & Africa"))
            {
                facc = facc.Replace("Middle East & Africa", "ME & A");
            }
            if (facc.Contains("Commercial ABS"))
            {
                facc = facc.Replace("Commercial ABS", "ABS");
            }
            if (facc.Contains("Russia & CIS"))
            {
                facc = facc.Replace("Russia & CIS", "RU&CIS");
            }
            if (facc.Contains("Russia & CIS"))
            {
                facc = facc.Replace("Russia & CIS", "RU&CIS");
            }
            if (facc.Contains("Central & Eastern Europe"))
            {
                facc = facc.Replace("Central & Eastern Europe", "CEE");
            }
            if (facc.Contains("Aerospace & Defense"))
            {
                facc = facc.Replace("Aerospace & Defense", "Aero");
            }
            if (facc.Contains("Agricultural Products"))
            {
                facc = facc.Replace("Agricultural Products", "Agri Prod");
            }
            if (facc.Contains("Consumer Products"))
            {
                facc = facc.Replace("Consumer Products", "Consumer Prod");
            }
            if (facc.Contains("Sovereign & Public Finance"))
            {
                facc = facc.Replace("Sovereign & Public Finance", "Sovereign");
            }
            if (facc.Contains("Media & Publishing"))
            {
                facc = facc.Replace("Media & Publishing", "Media");
            }

            if (facc.Contains("AUSTRALIA"))
            {
                facc = facc.Replace("AUSTRALIA", "AU");
            }
            if (facc.Contains("BERMUDA"))
            {
                facc = facc.Replace("BERMUDA", "BM");
            }
            if (facc.Contains("BRITAIN"))
            {
                facc = facc.Replace("BRITAIN", "GBR");
            }
            if (facc.Contains("BRAZIL"))
            {
                facc = facc.Replace("BRAZIL", "BR");
            }

            if (facc.Contains("CANADA"))
            {
                facc = facc.Replace("CANADA", "CA");
            }
            if (facc.Contains("CHINA"))
            {
                facc = facc.Replace("CHINA", "CN");
            }
            if (facc.Contains("CROATIA"))
            {
                facc = facc.Replace("CROATIA", "CR");
            }
            if (facc.Contains("DENMARK"))
            {
                facc = facc.Replace("DENMARK", "DK");
            }
            if (facc.Contains("FINLAND"))
            {
                facc = facc.Replace("FINLAND", "FI");
            }
            if (facc.Contains("FRANCE"))
            {
                facc = facc.Replace("FRANCE", "FR");
            }
            if (facc.Contains("GERMANY"))
            {
                facc = facc.Replace("GERMANY", "GE");
            }
            if (facc.Contains("HONG KONG"))
            {
                facc = facc.Replace("HONG KONG", "HK");
            }
            if (facc.Contains("HUNGARY"))
            {
                facc = facc.Replace("HUNGARY", "");
            }
            if (facc.Contains("INDIA"))
            {
                facc = facc.Replace("INDIA", "IN");
            }
            if (facc.Contains("INDONESIA"))
            {
                facc = facc.Replace("INDONESIA", "ID");
            }
            if (facc.Contains("IRELAND"))
            {
                facc = facc.Replace("IRELAND", "IE");
            }
            if (facc.Contains("ITALY"))
            {
                facc = facc.Replace("ITALY", "IT");
            }
            if (facc.Contains("JAPAN"))
            {
                facc = facc.Replace("JAPAN", "JP");
            }
            if (facc.Contains("KUWAIT"))
            {
                facc = facc.Replace("KUWAIT", "KW");
            }
            if (facc.Contains("LUXEMBOURG"))
            {
                facc = facc.Replace("LUXEMBOURG", "LU");
            }
            if (facc.Contains("MEXICO"))
            {
                facc = facc.Replace("MEXICO", "MX");
            }
            if (facc.Contains("NETHERLANDS"))
            {
                facc = facc.Replace("NETHERLANDS", "NE");
            }
            if (facc.Contains("NORWAY"))
            {
                facc = facc.Replace("NORWAY", "NO");
            }
            if (facc.Contains("OMAN"))
            {
                facc = facc.Replace("OMAN", "OM");
            }
            if (facc.Contains("PERU"))
            {
                facc = facc.Replace("PERU", "PE");
            }
            if (facc.Contains("PHILIPPINES"))
            {
                facc = facc.Replace("PHILIPPINES", "PH");
            }
            if (facc.Contains("PORTUGAL"))
            {
                facc = facc.Replace("PORTUGAL", "PT");
            }
            if (facc.Contains("RUSSIA"))
            {
                facc = facc.Replace("RUSSIA", "RU");
            }
            if (facc.Contains("SINGAPORE"))
            {
                facc = facc.Replace("SINGAPORE", "SG");
            }
            if (facc.Contains("SOUTH KOREA"))
            {
                facc = facc.Replace("SOUTH KOREA", "KR");
            }
            if (facc.Contains("SPAIN"))
            {
                facc = facc.Replace("SPAIN", "SP");
            }
            if (facc.Contains("SRI LANKA"))
            {
                facc = facc.Replace("SRI LANKA", "SR");
            }
            if (facc.Contains("SWEDEN"))
            {
                facc = facc.Replace("SWEDEN", "SE");
            }
            if (facc.Contains("SWITZERLAND"))
            {
                facc = facc.Replace("SWITZERLAND", "SW");
            }
            if (facc.Contains("THAILAND"))
            {
                facc = facc.Replace("THAILAND", "TH");
            }
            if (facc.Contains("UNITED STATES"))
            {
                facc = facc.Replace("UNITED STATES", "US");
            }
            if (facc.Contains("WESTERN EUROPE"))
            {
                facc = facc.Replace("WESTERN EUROPE", "WE");
            }

            if (facc.Contains("("))
            {
                string regex = "(\\[.*\\])|(\".*\")|('.*')|(\\(.*\\))";
                facc = Regex.Replace(facc, regex, "");

            }
            // DataTable dt = new DataTable(facc);
            var dt = new DataTable(facc);




            dt.Columns.Add("Date", typeof(string));
            dt.Columns.Add("Market Value");
            dt.Columns.Add("Interest Accrued");
            dt.Columns.Add("GainLoss");
            dt.Columns.Add("CashFlow");
            dt.Columns.Add("EOP Weightage");
            dt.Columns.Add("BOP Weightage");
            dt.Columns.Add("Return");
            dt.Columns.Add("Cum_Return");
            dt.Columns.Add("Contribution");
            dt.Columns.Add("Cum_contribution");
            dt.Columns.Add("annualised");
            dt.Columns.Add("premarket");
            dt.Columns.Add("preinterest");
            dt.Columns.Add("inflow");
            dt.Columns.Add("gainlost");

            List<Attribute_2f> returnlist = Attribute_2f.getInfo(ha, acc, preDateArray, DateArray, PreDateList, DateList, ConvertType, "Monthly", clickfactor1);
            foreach (Attribute_2f entity in returnlist)
            {
                if (p != 0)
                {
                    if (y == returnlist.Count())
                    {

                        dt = new DataTable(facc);
                        dt.Columns.Add("Date", typeof(string));
                        dt.Columns.Add("Market Value");
                        dt.Columns.Add("Interest Accrued");
                        dt.Columns.Add("GainLoss");
                        dt.Columns.Add("CashFlow");
                        dt.Columns.Add("EOP Weightage");
                        dt.Columns.Add("BOP Weightage");
                        dt.Columns.Add("Return");
                        dt.Columns.Add("Cum_Return");
                        dt.Columns.Add("Contribution");
                        dt.Columns.Add("Cum_contribution");
                        dt.Columns.Add("annualised");
                        dt.Columns.Add("premarket");
                        dt.Columns.Add("preinterest");
                        dt.Columns.Add("inflow");
                        dt.Columns.Add("gainlost");
                        y = 0;
                    }
                }
                DataRow row1 = dt.NewRow();
                //foreach of your properties
                row1["Date"] = entity.getDate().Substring(0, 4) + "/" + entity.getDate().Substring(4, 2) + "/" + entity.getDate().Substring(6, 2);
                row1["Market Value"] = String.Format("{0:C}", entity.getMarketValue());
                row1["Interest Accrued"] = String.Format("{0:C}", entity.getIntAccrued());
                row1["CashFlow"] = String.Format("{0:C}", entity.getinoutflow());
                row1["GainLoss"] = String.Format("{0:C}", entity.getGainLoss());
                row1["EOP Weightage"] = String.Format("{0:P2}", entity.getWeightage());
                row1["BOP Weightage"] = String.Format("{0:P2}", entity.getdop_weightage_gross());
                row1["Return"] = String.Format("{0:P2}", entity.getAttrReturn() - 1);
                row1["Contribution"] = String.Format("{0:P2}", entity.getContribution());
                row1["premarket"] = String.Format("{0:C}", entity.getpmarketValue());
                row1["preinterest"] = String.Format("{0:C}", entity.getPintAccrued());
                row1["inflow"] = String.Format("{0:C}", entity.getinoutflow());
                row1["gainlost"] = String.Format("{0:C}", entity.getGainLoss());
                row1["Cum_Return"] = String.Format("{0:P2}", entity.getCum_return() - 1);
                row1["BOP Weightage"] = String.Format("{0:P2}", entity.getweightage_gross());
                row1["annualised"] = String.Format("{0:P2}", entity.getannualised());
                row1["Cum_contribution"] = String.Format("{0:P2}", entity.getCum_contribution());
                y = y + 1;                        
                dt.Rows.Add(row1);
            }
            ds.Tables.Add(dt);
            y = 0;
        }

       //excel workbook
        using (XLWorkbook wb = new XLWorkbook())
        {
            string FileName = fromYear.ToString() + fromMonth.ToString() + "-" + toYear.ToString() + toMonth.ToString() + "(" + cbattr.ToString() + ")" + ".xlsx";

            if (FileName.Contains("cc.[AssetClsname]"))
            {
                FileName = FileName.Replace("cc.[AssetClsname]", "AssetClsname");
            }
            if (FileName.Contains("cc.[AssetClsname_IMA]"))
            {
                FileName = FileName.Replace("cc.[AssetClsname_IMA]", "AssetClsname_IMA");
            }
            if (FileName.Contains(","))
            {
                FileName = FileName.Replace(",", " ");

                foreach (DataTable dt in ds.Tables)
                {
                    var ws = wb.Worksheets.Add(dt.TableName);
                    ws.Cell(1, 1).InsertTable(dt);
                    ws.Columns().AdjustToContents();

                    ws.Tables.FirstOrDefault().ShowAutoFilter = false;
                    ws.Clear(XLClearOptions.Formats);             
                }
                p++;
                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=" + FileName);

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

以下是一些图片:

[Table format]

[Moving multiple worksheets error]

0 个答案:

没有答案