After adding all I want to a newly created excel file with epplus, how do I open it only? I don't want to save the file first then open it, is this possible? I want it to just open and let the user decide if he wants to save it or not.
The only code i've found and tried so far generates a file name, saves the excel file, and then open it.
Byte[] bin = p.GetAsByteArray();
string file = Guid.NewGuid().ToString() + ".xlsx";
File.WriteAllBytes(file, bin);
ProcessStartInfo pi = new ProcessStartInfo(file);
Process.Start(pi);
EPPlus is generating the xml in a renamed zip file so there is no mechanism to transfer it to Excel without saving it somewhere. But you can always save to the users temp folder - this is what most programs have to do at some point in order to transfer files between each other. Can do something like this using System.IO.Path.GetTempPath():
[TestMethod]
public void TempFolderTest()
{
var path = Path.Combine(Path.GetTempPath(), "temp.xlsx");
var tempfile = new FileInfo(path);
if (tempfile.Exists)
tempfile.Delete();
//Save the file
using (var pck = new ExcelPackage(tempfile))
{
var ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells[1, 2].Value = "Excel Test";
pck.Save();
}
//open the file
Process.Start(tempfile.FullName);
}
(taken from: Open ExcelPackage Object with Excel application without saving it on local file path)
it's not possible you can't Create a temporary excel file with epplus
Related
I can't figure out why this isn't working with a XLTX file. My code is wokring quite well with XLSX files.
/// <summary>
/// Copies the template file and renames the new one.
/// </summary>
/// <param name="sourceFilePath"></param>
private void CopyTemplateFile(string sourceFilePath)
{
string strSheetName = "";
DialogResult result;
result = MyDialog.ShowDialog("New File - Dialog", "Bitte Name eingeben", "Neue Datei erstellen?", "=FOR1+RBT1", "Ok", "Cancel", ref strSheetName);
if (result == DialogResult.Yes)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Template (*.xltx)|*.xltx|Excel File (*.xlsx)|*.xlsx";
sfd.FileName = strSheetName;
DialogResult ergebnis = sfd.ShowDialog();
if (ergebnis == DialogResult.OK)
{
string path = sfd.FileName;
//string tmp = path.Substring(path.LastIndexOf('\\')+1);
System.IO.File.Copy(sourceFilePath, path);
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(path, ReadOnly: false);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
ws.Name = strSheetName;
ws.Range[Statics.ANLAGE_ORT_CELL].Cells.Value2 = "'" + strSheetName;
string stAnlage = strSheetName.Substring(1);
string[] abc = stAnlage.Split('+');
ws.Range["A50"].Cells.Value2 = abc[0];
ws.Range["B50"].Cells.Value2 = abc[1];
wb.SaveAs(path);
wb.Close();
app.Quit();
Marshal.ReleaseComObject(app);
}
}
}
I'm using Microsoft.Office.Interop.Excel, a open file dialog for sourceFilePath, a save file dialog for path. The changes of sheet.name and cell values aren't saved if a XLTX is used.
Maybe someone of you guys knows the issue.
The issue is this line:
wb.SaveAs(path);
According to the documentation of the Workbook.SaveAs method you can/should give the following parameters:
FileName
A string that indicates the name of the file to be saved. You can include a full path; if you don't, Microsoft Excel saves the file in the current folder.
FileFormat
The file format to use when you save the file. For a list of valid choices, see the XlFileFormat enumeration. For an existing file, the default format is the last file format specified; for a new file, the default is the format of the version of Excel being used.
Actually both are optional, but if you omit the FileName Excel will use the standad file name and the "current folder" who knows which one this is, and if you omit the FileFormat then Excel would use the last file format that was specified or for new files the standard format which is a normal xlsx (in recent versions of Excel).
Another thing is that the file extension you use .xltx, .xlsx, .xlsm necessarily needs to fit the correct file format. If it doesn't Excel throws an error. This is actually what you run into when you got the Error:
COMException: Additional information: This extension cannot be used
with the selected file type. Change the file extension in the 'File
Name' text box, or choose a different file type by changing the 'Save
As' selection.
Because you only specified the FileName and you chose .xltx as file extension but the default file format is usually xlOpenXMLWorkbook according to the list in XlFileFormat enumeration.
So if you lookup in that list which file formats you can use with the extension .xltx then you will only find one valid file format and that is xlOpenXMLTemplate. So this is what you need to specify:
'example for path/filename you got from your dialog box
path = "C:\YourPath\YourFileName.xltx"
wb.SaveAs(FileName:=path, FileFormat:=xlOpenXMLTemplate);
I have some code that is suppose to enter some values into several excel workbooks. Right now the program doesn't even put any values into the workbooks and only saves them. Even like this i get this error when opening the files: Excel cannot open the file **.xlsm because the file format or file extension is not valid. Verify that the file has been corrupted and that the file extension matches the format of the file.
I have writen many programs that work with excel files and never had this problem. In the code you can see that i basically just go through a for loop and save the file.
try
{
fileInfo = new FileInfo(Path.GetDirectoryName(Application.StartupPath) + '\\' + partners[partner].partnerName + #"\PDP_ExSumm_" + partners[partner].partnerName + ".xlsm");
using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[1];
for (int cell = 0; cell < ExSummCells.Count; cell++)
{
if (ExSummCells[cell] != "")
{
// worksheet.Cells[ExSummCells[cell]].Value = partners[partner].exSummData[partner];
}
excelPackage.Save();
}
}
After exporting data into an Excel workbook with macros (xlsm), I run the macro and then remove the macro in order to be able to save the workbook as xlsx. For removing macros, I open the xlsm as zip archive (via C# ZipFile class), remove the entry "xl/vbaProject.bin" and remove a relation within "xl/_rels/workbook.xml.rels". Then I rename the file from xlsm to xlsx. That works fine so far but when I open the xlsx file in Excel, I get "Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file", so there seems something to be missing in order to completely remove the vba code within the workbook. Can anyone help me here?
const string vbaProjectEntryName = "xl/vbaProject.bin"; // Contains the VBA code
const string relationsEntryName = "xl/_rels/workbook.xml.rels"; // Relation/Link to the vba project
using (var zip = ZipFile.Open(fileName, ZipArchiveMode.Update))
{
var entry = zip.GetEntry(vbaProjectEntryName);
if (entry != null)
{
entry.Delete();
entry = zip.GetEntry(relationsEntryName);
if (entry != null)
{
var contents = string.Empty;
using (var streamReader = new StreamReader(entry.Open()))
{
contents = streamReader.ReadToEnd();
}
var relationText = "<Relationship Id=\"rId6\" Type=\"http://schemas.microsoft.com/office/2006/relationships/vbaProject\" Target=\"vbaProject.bin\"/>";
contents = contents.Replace(relationText, string.Empty);
entry.Delete();
entry = zip.CreateEntry(relationsEntryName);
using (var streamWriter = new StreamWriter(entry.Open()))
{
streamWriter.Write(contents);
}
}
}
}
I'm having an issue saving excel files as CSV's and preserving the encoding in C#. Specifically, the following takes an excel file and saves it as a csv file with the same name, which is passed to the loadCsvData function, whose job is to insert the data into a database in an organized fashion. My issue is that the excel file contains fractional symbols which are not recognized in a csv format, unless i MANUALLY open each .xml and save as csv (for some reason this works while the Microsoft.Office.Interop.Excel.Application method SaveAs() does not):
List<string[]> data = new List<string[]>();
string fileName = (date.ToString("MM/dd/yyyy") + ".csv").Replace("/","");
string excelFileName = (date.ToString("MM/dd/yyyy") + ".xml").Replace("/","");
System.Console.WriteLine("Processing file: " + fileName);
System.Console.ReadLine();
// Open excel and save as csv. Then process the data
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(#"C:\Users\TAG\Desktop\TIP holdings\" + excelFileName);
workBook.SaveAs(#"C:\Users\TAG\Desktop\TIP holdings\CSV Data\" + fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);
workBook.Close(false,"",true);
data = loadCsvData(fileName);
insertData(data);
I am using DotNetZip.
What I need to do is to open up a zip files with files from the server.
The user can then grab the files and store it locally on their machine.
What I did before was the following:
string path = "Q:\\ZipFiles\\zip" + npnum + ".zip";
zip.Save(path);
Process.Start(path);
Note that Q: is a drive on the server. With Process.Start, it simply open up the zip file so that the user can access all the files. I like to do the same but not store the file on disk but show it from memory.
Now, instead of storing the zip file on the server, I like to open it up with MemoryStream
I have the following but does not seem to work
var ms = new MemoryStream();
zip.Save(ms);
but not sure how to proceed further in terms of opening up the zip file from a memory stream so that the user can access all the files
Here is a live piece of code (copied verbatim) which I wrote to download a series of blog posts as a zipped csv file. It's live and it works.
public ActionResult L2CSV()
{
var posts = _dataItemService.SelectStuff();
string csv = CSV.IEnumerableToCSV(posts);
// These first two lines simply get our required data as a long csv string
var fileData = Zip.CreateZip("LogPosts.csv", System.Text.Encoding.UTF8.GetBytes(csv));
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "LogPosts.zip",
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, "application/octet-stream");
}
You can use:
zip.Save(ms);
// Set read point to beginning of stream
ms.Position = 0;
ZipFile newZip = ZipFile.Read(ms);
See the documentation for Create a zip using content obtained from a stream.
using (ZipFile zip = new ZipFile())
{
ZipEntry e= zip.AddEntry("Content-From-Stream.bin", "basedirectory", StreamToRead);
e.Comment = "The content for entry in the zip file was obtained from a stream";
zip.AddFile("Readme.txt");
zip.Save(zipFileToCreate);
}
After saving it, you can then open it up as normal.