hmk
hmk

Reputation: 969

how to Design the exported excel in asp.net?

I am exporting gridview data to excel but that excel file add the some lable text and textbox values and format also taken , pls give how to design the excel code in asp.net. I am writing like this

Upvotes: 0

Views: 3296

Answers (1)

KorsG
KorsG

Reputation: 739

Take a look at this awesome tool: http://www.carlosag.net/Tools/ExcelXmlWriter/

Futhermore, the author also created a code generator, which generates .net code from a provided excel sheet(formatting, layout and so on)
http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx

Here's some code that generates an excel file from a datatable (converted vb code, as pr. request by poster)

        CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();
        book.ExcelWorkbook.ProtectWindows = false;

        book.ExcelWorkbook.ProtectStructure = false;

        var styles = book.Styles;
        WorksheetStyle defaultStyle = styles.Add("Default");
        var defStyles = defaultStyle;
        defStyles.Name = "Normal";
        defStyles.Font.FontName = "Calibri";
        defStyles.Font.Size = 11;
        defStyles.Font.Color = "#000000";
        defStyles.Alignment.Vertical = StyleVerticalAlignment.Bottom;

        Worksheet sheet = book.Worksheets.Add("Sheet1");
        sheet.Table.DefaultRowHeight = 15f;
        sheet.Table.FullColumns = 1;
        sheet.Table.FullRows = 1;
        DataTable dt = new DataTable();  //=  your datatable

        //Header
        WorksheetRow HeaderRow = sheet.Table.Rows.Add();
        foreach (DataColumn col in dt.Columns)
        {
            HeaderRow.Cells.Add(col.ColumnName.ToString());

        }
        //Body
        foreach (DataRow dr in dt.Rows)
        {
            WorksheetRow row = sheet.Table.Rows.Add();
            foreach (DataColumn cols in dt.Columns)
            {
                  row.Cells.Add(dr[cols.ColumnName.ToString()].ToString());
            }
        }

        sheet.Options.Selected = true;
        sheet.Options.ProtectObjects = false;
        sheet.Options.ProtectScenarios = false;

        book.Save("path to file");

Upvotes: 2

Related Questions