model view controller - ReportViewer export to Excel with password -
i had code in mvc exports out excel file how add password excel file?
my code:
public actionresult report(string id) { localreport lr = new localreport(); string path = path.combine(server.mappath("~/report"), "reportstatearea.rdlc"); if (system.io.file.exists(path)) { lr.reportpath = path; } else { return view("index"); } list<statearea> cm = new list<statearea>(); using (mydatabaseentities dc = new mydatabaseentities()) { cm = dc.stateareas.tolist(); } reportdatasource rd = new reportdatasource("mydataset", cm); lr.datasources.add(rd); string reporttype = id ; string mimetype; string encoding; string filenameextension; string deviceinfo = "<deviceinfo>" + " <outputformat>" + id + "</outputformat>" + " <pagewidth>8.5in</pagewidth>" + " <pageheight>11in</pageheight>" + " <margintop>0.5in</margintop>" + " <marginleft>1in</marginleft>" + " <marginright>1in</marginright>" + " <marginbottom>0.5in</marginbottom>" + "</deviceinfo>"; warning[] warnings; string[] streams; byte[] renderedbytes; renderedbytes = lr.render( reporttype, deviceinfo, out mimetype, out encoding, out filenameextension, out streams, out warnings); return file(renderedbytes, mimetype); }
you can use filestream class write renderedbytes
on file.
dim strexcelfile string = "c:\yourpathto\excelfile.xls" dim fs new filestream(strexcelfile, filemode.create) fs.write(renderedbytes, 0, renderedbytes.length) fs.close() fs.dispose()
then use microsoft.office.interop.excel.dll add password existing workbook:
dim appexcel excel.application dim wbexcel excel.workbook appexcel = new excel.application wbexcel = appexcel.workbooks.open(strexcelfile) wbexcel.password = "yourpassword" appexcel.displayalerts = false wbexcel.saveas(strexcelfile) appexcel.displayalerts = true wbexcel.close()
i used displayalerts suppress prompts , alert messages while using saveas
overwrite existing file; when message requires response, microsoft excel chooses default response.
my code in vb.net can translate in c#.
Comments
Post a Comment