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();
}
}
Related
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 want to split one large Excel file to few smaller and accessible files.
I already tried to use this code but the files are not accessible:
using (System.IO.StreamReader sr = new System.IO.StreamReader("path"))
{
int fileNumber = 0;
while (!sr.EndOfStream)
{
int count = 0;
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("other path" + ++fileNumber + ".xlsx"))
{
sw.AutoFlush = true;
while (!sr.EndOfStream && ++count < 20000)
{
sw.WriteLine(sr.ReadLine());
}
}
}
}
Any ideas?
thanks.
Files, other than text files, don't work this way. You can't simply cut at a certain point and obtain a working copy.
As for Excel files, you may look into the following tutorial, which illustrates how to automate Excel from C#:
https://support.microsoft.com/en-us/help/302084/how-to-automate-microsoft-excel-from-microsoft-visual-c--net
Basically, what you want to do is open your large Excel file, decide where you want to split it (every n rows, every n sheets and so on), read each portion and write into a newly created xlsx.
I am trying to export Excel files to PDF. I am having success with this using the Microsoft.Office.Interop namespace. I am now trying to find out how to exclude tabs that are marked hidden, so that they are not within the PDF> Hase anyone done this or knows how to do this? My code is shown below that I am currently using.
string inFile = #"C:\Users\casey.pharr\Desktop\testPDF\3364850336.xls";
string outFile = #"C:\Users\casey.pharr\Desktop\testPDF\3364850336_noHidden_out.pdf";
string tempFile = #"C:\Users\casey.pharr\Desktop\testPDF\temp.xls";
try
{
//first copy original file to temp file to work with
File.Copy(inFile,tempFile, true);
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
app.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook wkb = app.Workbooks.Open(tempFile);
for(int x = app.Sheets.Count-1; x-1 > 1; x--)
{
Excel._Worksheet sheet = (Excel._Worksheet)app.Sheets[x];
//now delete hidden worksheets from work book. This is why we are using tempFile
if (sheet.Visible == Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden || sheet.Visible == Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetVeryHidden && sheet != null)
{
//is sheet hidden. If so remove it so not part of converted file
sheet.Delete();
}
}
wkb.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outFile);
wkb.Close(false);
app.Quit();
//return outputLocation;
The error that occurs on calling .Delete() is below:
Exception from HRESULT: 0x800A03EC
enter code here
So we can convert the pdf's fine, but not remove or exclude hidden worksheets. I went the route to try to delete them then convert the entire file, but not working.
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
I wrote this code below
string filePath = #"C:\report_data.xlsx";
// Saves the file via a FileInfo
var file = new FileInfo(filePath);
// Creates the package and make sure you wrap it in a using statement
using (var package = new ExcelPackage(file))
{
// Adds a new worksheet to the empty workbook
OfficeOpenXml.ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Report System - " + DateTime.Now.ToShortDateString());
// Starts to get data from database
for (int row = 1; row < 10; row++)
{
// Writes data from sql database to excel's columns
for (int col = 1; col < 10; col++)
{
worksheet.Cells[row, col].Value = row * col;
}// Ends writing data from sql database to excel's columns
}// Ends getting data from database
// Saves new workbook and we are done!
package.Save();
}
When i opened the file , it had nothing and the page was blank. But when i saw the file size , it increased . Why was the page blank while the file size increased and how can i write data to it ?
Remark : When i tried deleting the existing file and run a program, the program generated the file and the file had values displayed in the columns . On the other hand , i tried creating file first and then run the program and the result was blank like i said above .
I found out the answer . I just changed the line at
OfficeOpenXml.ExcelWorksheet worksheet =
package.Workbook.Worksheets.Add("Report System - " +
DateTime.Now.ToShortDateString());
to
OfficeOpenXml.ExcelWorksheet worksheet =
package.Workbook.Worksheets["Sheet1"];
and it worked !!.
Because Sheet1 is the default name of worksheet and it existed in my file at line:
string filePath = #"C:\report_data.xlsx";
Actually, in this case, package.Workbook.Worksheets.Add means to add the worksheet's name and I found that it didn't have to add the worksheet's name because it already exists.