Reputation: 429
Does someone knows, is it possible to open Microsoft Excel from unsaved file? From memory stream for example?
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
using (var ms = new MemoryStream())
{
//IS IT POSSIBLE TO OPEN EXCEL BUT FROM UNSAVED MEMORYSTREAM?
//Process.Start(EXCEL MS HERE);
}
OR, save file to some temporary folder and then open it by Excel, BUT required from user to 'Save' and 'SaveAs' actions.
Main goal: Open Microsoft Excel application from C# code with prepared sheets and say that user must save it like this document is a new one.
Upvotes: 4
Views: 5136
Reputation: 911
I don't know that you can load an Excel file via MemoryStream
like you're wanting, but what you could do is the following:
ChangeFileAccess
method (or whatever equivalent you have) to set the workbook to readonly. So, if they want a copy of it, they will need to save it.Process.Start(...)
to launch excel.exe with the argument of the newly created Excel workbook.Process.WaitForExit()
until the user is done doing whatever it is they need to doProcess.WaitForExit()
Upvotes: 0
Reputation: 12811
No, there is no way to directly open a workbook from memory. However, Application.Workbooks.Open
supports URLs, so you could create an in-process HTTP server and serve it that way. That's probably overkill for most purposes.
Usually when I want to ship pre-packaged documents, I will either ship the documents as standalone files, or write them from memory to a temporary location. In either case, you will want to prevent the user from saving the file in the source location. You can do this two ways:
(Preferred) Ship your documents as templates (.xltx) instead of documents, and then use Application.Workbooks.Add
.
Application.Workbooks.Add "X:\path\to\template.xltx"
Open the document in read-only mode, either by setting the file to read-only or by using the ReadOnly
argument of Application.Workbooks.Open
. A read-only document can be edited but not saved.
Application.Workbooks.Open "X:\path\to\document.xlsx", , True
Upvotes: 1
Reputation: 1237
You would use Excel Interop to do this.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook workbook = excel.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet sheet = workbook.Sheets[1];
sheet.Cells[1, 1] = "Hello World!";
This will open Excel on the user's machine without saving the workbook. The user then has the option to change whatever is needed and then save the workbook manually.
Upvotes: 2