unable to save excel file using saveAs method in c# - c#

I'm saving an excel file using SaveAs method in c#. but it shows error like :
Additional information: The file could not be accessed. Try one of the following:
• Make sure the specified folder exists.
• Make sure the folder that contains the file is not read-only.
• Make sure the file name does not contain any of the following characters: < > ? [ ] : | or *
• Make sure the file/path name doesn't contain more than 218 characters.
my code is this :
string savepath = AppDomain.CurrentDomain.BaseDirectory + #"\Salary Slips\a.xlsx";
xlwbOP.SaveAs(savepath, Excel.XlFileFormat.xlExcel12);
the savepath variable have value
savepath="D:\Application\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\Salary Slips\a.xlsx"
and the directory :"D:\Application\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\Salary Slips\" is exsits

If I'm remembering correctly (it's been awhile), you should check to makes sure the file exists before attempting to save. You might also want to wrap this in a try-catch block to handle exceptions caused by problems with permissions or paths not existing.
string savepath = AppDomain.CurrentDomain.BaseDirectory + #"\Salary Slips\a.xlsx";
try
{
if(!File.Exists(savepath))
xlwbOP.SaveAs(savepath, Excel.XlFileFormat.xlExcel12);
else
xlwbOP.Save();
}
catch
{ /*input your exception handling here*/ }
I also recommend verifying that your path doesn't contain invalid characters before trying to use it to save.
You may also want to look into using SaveCopyAs(string) for saving copies as new files.

As described in Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error, the proper enum to save as .xlsx is not Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook
The correct way, here also incorporating the Missing.Value is therefore:
var missing = System.Reflection.Missing.Value;
var savepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Salary Slips", "a.xlsx");
xlwbOP.SaveAs(savepath, Excel.XlFileFormat.xlOpenXMLWorkbook, missing,
missing, false, false, missing, missing, true, missing, missing, missing);
Credits to SO user MoonKnight.

Related

Office Interop Word Mail Merge throws DISP_E_TYPEMISMATCH exception

My issue involves a word file which has a macro embedded from another company which we have to remove and then set a new data source path (xlsx spreadsheet). The macro must be removed because it already sets the data source which is not available anymore when we get the file. Now I'm looking for a possibility to change the data source (path) of said word file programmatically but can't find any that does the job only VB Code. We don't want to write another macro and inject it we only want to change the data source path before the user downloads the file. I'm free to use any library.
Can anyone please suggest me a way to change the data source of a word file programmatically?
Update:
I'm now working with the MS Office Interop Word Library and achieved what I was looking for (changing data source) but unfortunately the excel file is damaged afterwards and can't be opened anymore saying "invalid data format".
Code below:
Application app = new Application();
Document officeDoc = app.Documents.Open(toBeMerged);
var srcFile = #"C:\DataSource.xlsx";
FileInfo fileInfo = new FileInfo(srcFile)
{
IsReadOnly = false
};
officeDoc.MailMerge.CreateDataSource(srcFile);
officeDoc.Save();
officeDoc.Close();
app.Quit();
Update 2
I've set all the needed parameters.
officeDoc.MailMerge.CreateDataSource(missing, missing, missing, missing, missing, missing, missing, missing, srcFile);
The parameters are as following:
CreateDataSource(Name, PasswordDocument, WritePasswordDocument, HeaderRecord, MSQuery, SQLStatement, SQLStatement1, Connection, LinkToSource)
This throws a System.Runtime.InteropServices.COMException 0x80020005 (DISP_E_TYPEMISMATCH) exception but the word gets successfully generated. When I put the srcFile variable at the begining where it should belong the excel file gets like above mentioned damaged despite giving all the optional parameters.
Thanks in advance helping me solving my last issue.

Can we create Excel File using File.Create?

I want to create an Excel file, at specific location and specific name in c#.
Can we use File.Create("Filename.xlsx") for this?
This creates the file, but when we try to open it; it says problem in extension.
I have tried another way, using excelApp. But that way, it creates Excel file default at "~Documents\Sheet1.xlsx". So i can't specify location and filename in that case.
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(1);
The question is similar to - Specify Path and filename while creating excel
Since i am unable to comment, i have to ask again.
I have tried the answer provided in link.
My code:
Excel.Application excelApp = new Excel.Application();
object missing = System.Reflection.Missing.Value;
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(missing);
//....
Fill excelWorkbook after creating worksheets
....//
excelWorkBook.Save();
Now, as per suggestion, instead of Save, i have used SaveAs.
excelWorkBook.SaveAs(#"E:\\MyExcelBook\\abcd.xlsx",
Excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
It gives me error:
*The file could not be accessed. Try one of the following:\n\n• Make sure the specified folder exists. \n• Make sure the folder that contains the file is not read-only.\n• Make sure the file name does not contain any of the following characters: < > ? [ ] : | or \n• Make sure the file/path name doesn't contain more than 218 characters.
Please tell me where am i doing wrong?
Just because you save an "empty" file with an extension of .xlsx doesn't mean excel is able to read such a file. You can use OpenXML, ClosedXML (my preferred), interop (yucky) and I'm sure many other methods of creating an excel document
File.Create(...) is not much different than right clicking in file explorer, choosing new text document, and renaming it from "New Text Document.txt" to "New Text Document.xlsx". Yeah that extension is excel, but excel can't read an empty file that states it's an excel file.
You can use any of the libraries available to you to create excel files:
ClosedXML
OpenXML
Interop
etc. Most "Save" methods or "SaveAs" methods within these libraries would (probably) create the file in the working directory by default, but you can specify a directory to create them in as well.
Just as the answer in the linked question shows:
workbook.SaveAs(#"c:\documents\book1.xlsx",
Excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);

How to programmatically convert a .cal file to a .cg4?

In windows explorer I am able to just change the file extension of a .cal file to a .cg4 file. When I do it I get a warning; "changing the file extension might render the file useless, do you still wish to change?" or something like that (OS not in english), but if I click "yes" it works.
But trying to do this programmatically with C# doesn't work. I get an error that states: "The given path's format is not supported."
I'm using File.Move for renaming/converting and that's where the error occurs.
File.Move(directory + fileNameWithoutExtension + ".cal", directory + fileNameWithoutExtension + ".cg4");
What can I do?
does this work?
var pathSource = System.IO.Path.Combine(directory, fileNameWithoutExtension, ".cal");
var pathDest = System.IO.Path.Combine(directory, fileNameWithoutExtension, ".cg4");
File.Move(pathSource, pathDest);
if it also throws an error, check if
fileNameWithoutExtension
already contains the data of
directory

Excel InterOp: How to WorkBook.SaveAs using absolute path when ":" is not allowed?

I'm trying to save a workbook from memory using the following code:
this.Target.WorkBook.SaveAs(this.Target.WorkBookPath, Interop.XlFileFormat.xlWorkbookNormal,
Type.Missing, Type.Missing,
Type.Missing, Type.Missing,
Interop.XlSaveAsAccessMode.xlNoChange,
Type.Missing,Type.Missing,Type.Missing,Type.Missing);
Where this.Target.WorkBookPath is read from the config file as:
D:\Devzone\rpt_SalesMargins2
But Im getting this error message:
The file could not be accessed. Try one of the following:\n\n• Make
sure the specified folder exists. \n• Make sure the folder that
contains the file is not read-only.\n• Make sure the file name does
not contain any of the following characters: < > ? [ ] : | or
*\n• Make sure the file/path name doesn't contain more than 218 characters.
So if I cant use ":" then how can I specify D:\ ?
UPDATE / SANITY CHECK
In this image the file is called rego, i have tried several random names and all work as relative paths but fail when absoluted.
I don't think the problem is with the : as a drive separator. From Microsoft Support:
For example, the path for a file might resemple the following:
'c:\excel\personal...[my workbook.xls]up_to_31_char_sheetname'!$A$1
Note This behavior will also occur if there is a square bracket in the path. (emphasis mine)
http://support.microsoft.com/kb/213983
They use an example of a bad path that includes a drive letter and say the bad thing is the [ in the path.
What is the full path you are trying to use?

Selection.InsertFile() not finding file despite it being in directory

I am experimenting with the Microsoft.Office.Interop.Word namespace to do some manipulation of docx files, specifically programmatically merging them.
I created a simple test harness to try out some of the functionality and I am getting a file not found error despite the file being in the executing directory.
All I am trying to do is merge two docx files, doc1.docx and doc2.docx respectively. Again I am just playing around with this functionality at this point so I created a simple C# console app and have the following:
using Word = Microsoft.Office.Interop.Word;
//and in my method:
object defaultTemplate = #"Normal.dotm";
object missing = System.Type.Missing;
object outputFile = "out.docx";
Word.Application wordApplication = new Word.Application();
//using the default Word template
Word._Document wordDocument = wordApplication.Documents.Add(defaultTemplate);
Word.Selection selection = wordApplication.Selection;
//add files manually. THIS is where things are failing
selection.InsertFile("doc1.docx");
selection.InsertFile("doc2.docx");
I get an exception with the message "This file could not be found." in my first call to InsertFile(). I am certain the files exist in my debug directory, which is where this program is running. MSDN explicitly states that if you don't provide a path with your parameter it uses the current directory. It finds the template Normal.dotm fine. I feel like I am missing something simple here but have been messing with it for over a half hour with no luck. Does anyone have any suggestions on what I should be doing here? Thanks for reading!
Make sure for your path is available. use GetCurrentDirectory() to be sure your current directory is what you want. else use full path.
You also might need to set the default file path.
MyWordApp.Application.Options.set_DefaultFilePath()

Categories

Resources