简体   繁体   中英

How to create new sheets on condition in excel file using c#

Following code works for me to generate only single excel file and single sheet in that.

I want to generate separate sheets for every CustomerOrders how can I do it?

List<MyData> Data = //code to get list of data

DataTable reportDataTable = new DataTable();
reportDataTable.Columns.Add("no");
reportDataTable.Columns.Add("Code");
int count =0

if (Data != null)
{
    foreach (MyData dataobj in Data)
    {
        count++;
        foreach (var innerdata in dataobj.CustomerData.OrderBy(t => t.Number))
        {
            foreach (var orderobj in dataobj.CustomerOrders)
            {
                DataRow row = reportDataTable.NewRow();
                row[0] = "No";
                row[1] = "Code"+count;                            
                reportDataTable.Rows.Add(row);
            }
        }
    }
}

GridView grid = new GridView();
grid.DataSource = reportDataTable;
grid.DataBind();

return new DownloadFileResult(grid, "MYEXCELFILE.xls");

public DownloadFileResult(GridView gv, string FileName)
{
    GridView = gv; // property
    fileName = FileName; //property
}

How do I generate those multiple sheets in one MYEXCELFILE.xls file?

For above i have used following link code 
http://www.codeproject.com/Articles/325103/MVC-Grid-to-Excel-file-download

Try this source code:

//Create an instance of the object that generates the Excel file
ExcelDocument xls = new ExcelDocument();

//Loop for each CustomerOrders
{
    //Add an worksheet for each CustomerOrders sheet
    ExcelWorksheet xlsSheet = new ExcelWorksheet();
    xlsSheet.setSheetName("CustomerOrders #no");
    xls.easy_addWorksheet(xlsSheet);

    //Create a dataset that contains the gridview datatable
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add((DataTable)gridView.DataSource);

    //Add the datatable
    xlsSheet.easy_insertDataSet(dataSet, "A1", true);
}

//Export Excel file
xls.easy_WriteXLSFile("MYEXCELFILE.xls ");

For formatting the cells see this link: http://www.easyxls.com/manual/FAQ/export-gridview-to-excel.html

This code uses EasyXLS library for generating Excel files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM