1
votes

How to protect password in excel while downloading excel file.

this.Response.AddHeader("Content-Disposition", "attachment; filename=Report With History.xls"); this.Response.ContentType = "application/vnd.ms-excel"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());

1
what do you mean protect password in excel?Nicolai
If try to open excel sheet then it ask password to open excel sheetBalaji Selvarajan

1 Answers

0
votes

Finally I found code:

    protected void Page_Load(object sender, EventArgs e)
    {

        DataSetToExcel(GetDataSet(), false);
    }

    private static DataSet GetDataSet()
    {
        DataSet ds = new DataSet();
        System.Data.DataTable dt = new System.Data.DataTable("Table");

        dt.Columns.Add("Name", Type.GetType("System.String"));
        dt.Columns.Add("Address", Type.GetType("System.String"));
        dt.Columns.Add("Phone", Type.GetType("System.String"));

        DataRow dr = dt.NewRow();
        dr["Name"] = "Balaji Selvarajan";
        dr["Address"] = "Reddiyur";
        dr["Phone"] = "000-000-0000";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = "Balaji S";
        dr["Address"] = "Kattumannar Koil";
        dr["Phone"] = "000-000-0000";
        dt.Rows.Add(dr);

        ds.Tables.Add(dt);
        return ds;
    }


    private static void DataSetToExcel(DataSet ds, Boolean generateIdentity)
    {
        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
        xlApp.Visible = false;
        Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        for (int k = 0; k < ds.Tables.Count; k++)
        {
            System.Data.DataTable dt = ds.Tables[k];
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Add(Missing.Value,
                            Missing.Value, Missing.Value, Missing.Value);
            ws.Name = dt.TableName;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (i == 0)
                        ws.Cells[1, j + 1] = dt.Columns[j].ColumnName;

                    ws.Cells[i + 2, j + 1] = (j == 0 && generateIdentity) ?
                                             (i + 1).ToString() : dt.Rows[i][j].ToString();
                }
            }
            ws.Protect("1", true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
        }
        wb.Protect("my", true, true);
        wb.Password = "Test";            
        wb.Close();

        xlApp.Visible = true;
    }