如何在下载时保护Excel中的密码?

时间:2014-05-06 08:59:24

标签: asp.net asp.net-mvc

下载excel文件时如何保护excel中的密码。

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 个答案:

答案 0 :(得分:0)

最后我找到了代码:

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