I am trying to save an excel with other name.
WB.SaveAs(AppDomain.CurrentDomain.BaseDirectory + #"Output\" + "Family" + #"\Item_" + entry.Key + ".xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,false, true, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
but if the entry.key is equal to 599, 863,868,875,868,881,882,902, then I am getting an error saying
ExportData Microsoft Excel cannot access the file
'C:\Naveen\Tool\bin\Debug\Output\Family\1CF3EF00'. There are several
possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
"1CF3EF00" this part is getting changed every time I run the code.
eg: 09E7EF00,E748EF00 etc
Do you get the same error if you specify another directory? like the temp? System.IO.Path.GetTempPath() + #"\Item_" + entry.Key + ".xlsx"
Related
I have some code that copies all sheets from one excel file into another. This code is as follows:
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook source = ExcelApp.Workbooks.Add(missing);
Microsoft.Office.Interop.Excel.Workbook destination = ExcelApp.Workbooks.Add(missing);
string file = #"C:\SomeExcelFile.xlsx";
source = ExcelApp.Workbooks._Open
(file, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
foreach (Microsoft.Office.Interop.Excel.Worksheet s in source.Worksheets)
{
s.Copy(Type.Missing, destination.Worksheets[destination.Worksheets.Count]);
}
In most cases this works as expected but there are two issues that I want to resolve. The first is that in one of the excel workbooks I am copying there is a column that is formatted like this:
$#,##0.00;[Red]-$#,##0.00
When running this through my code this column gets reformatted to this:
$#,##0.00_);[Red]($#,##0.00)
Is there a way I can retain the formatting of the original file?
Secondly, I'd like the widths of the columns to remain the same as the original file. Is this possible too?
This code is being used to merge multiple excel workbooks into a single file.
Thanks
I'm working with a legacy system that has components made several years ago (Excel macros) which I'm now trying to integrate into a more user friendly .net application. The files I am accessing are tab-delimited datasheets saved as __.xls so they're opened automatically by Excel when double-clicked.
Inside the sheet there are various dates in the format "dd/MM/yyyy", and when the file is opened normally (double clicked, right-click open, etc) via Excel 2003 (required version), the dates are interpreted as such. When I attempt to open the file using the Microsoft.Office.Interop.Excel (14.0.4756.1000) library however, (i.e. invoke via c#) using the following syntax:
eit_book = eit_books.Open(targetFile.FullName, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
the dates have their day and month switched, and all date math done in the aforementioned macros is done incorrectly. (As well as any dates where the day is greater than 12 are not even recognized as dates)
I.E. 04/01/2012 becomes 01/04/2012, this is presumably because the system has its regional settings set to "English (United States)", but I've made sure that the system's Regional Settings Short Date format is set to a custom value that matches the data in the spreadsheet ("dd/MM/yyyy"), and the problem only seems to occurs when the sheet is opened using the code above.
Any help would be very much appreciated. Thanks.
edit: The Operating System of the computer opening the files is Windows XP.
You need to use the OpenText method to open the file to be able to specify the date formats. Additionally, Excel remembers your previous preferences (when opening a text file, or converting text to columns), so you must explicitly specify most of the parameters for reliable outcomes.
My sample file is tab delimited with 3 columns, but I'm only specifying the date format for the first column.
The first line of text in my file is:
11/01/2001 12/01/2001 13/01/2001
The OpenText method doesn't return a Workbook, so I have to retrieve it by name afterwards:
int[] dateColInfo = new int[] {1, (int)XlColumnDataType.xlDMYFormat};
object[] fieldInfo = new object[] {dateColInfo};
eit_books.OpenText(path, Type.Missing, 1, XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierDoubleQuote, false, true, false, false, false, false, Type.Missing, fieldInfo, Type.Missing, Type.Missing, Type.Missing, Type.Missing, false);
eit_book = eit_books.get_Item(name);
Range rng = eit_book.Worksheets.get_Item(1).range("A1");
Console.WriteLine("{0} ISO Date: {1}", rng.Value, ((DateTime)rng.Value).ToString("yyyyMMdd"));
The output when dateColInfo[1] = XlColumnDataType.xlDMYFormat is:
11/01/2001 12:00:00 AM ISO Date: 20010111
The output when dateColInfo[1] = XlColumnDataType.xlMDYFormat is:
1/11/2001 12:00:00 AM - ISO Date: 20011101
When trying to run these lines:
var app = new Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(pathToFile, Type.Missing, true, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
I've got these problems:
1) I'm getting a message of "file conversion is in progress". Why do I need to convert something if all I want to do is just read a column from one of the work sheets.
2) I'm getting this error message:
why do I need to care which version created the excel?
3) In the very end I get an exception: "Too many different cell formats".
So is there something wrong with the way I'm using the open workbook method or is there another way to read a specific column from an excel file which contains several sheets and I only need to read data from a single specific sheet?
It might not be obvious to you but calling
new Excel.Application()
opens an instance of Excel (you may check it on the Task Manager). So if your version of Excel is not compatible with the file you are opening you get this error.
Since you are trying to open the Excel document with your Excel application, you DO care of what versions they are.
I think OpenXML SDK could help you with it.
I'm new to C# and trying to accomplish some simple excel manipulation through the interop library.
I'd like to delete a text value which always appears as a separate line below the actual data table (with a blank row between the table and the text). It's a 'rows selected.' count which prints out in an automated report. It always appears in the first column.
The error "COMexception unhandled - Cannot access read-only document - test1.xlsx" appears after the row is deleted and I try to Close() the workbook.
I cannot seem to release the workbook, I've tried a lot of random garbage collection methods found on other forums, but has anyone seen this before?
Appreciate the help!
EDIT - So the file isn't read-only until I start running the program. Once I run the program it becomes locked and read-only. It isn't closing/releasing the workbook...
EDIT - I ended up adding a Workbook.Save() function and using the Application object's Quit() function. This question was also very informative (similar question).
public void ExcelManip(string thisFileName)
{
Workbook workBook = _excelApp.Workbooks.Open(thisFileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
DeleteRowCount(ref workBook);
workBook.Save();
workBook.Close(false, Type.Missing, Type.Missing);
_excelApp.Application.Quit();
_excelApp.Quit();
//workBook.Close(true, thisFileName);//ERROR;Cannot access read-only document
//Marshal.ReleaseComObject(workBook);
//GC.Collect();
//GC.WaitForPendingFinalizers();
}
I ended up adding a Workbook.Save() function and using the Application object's Quit() function. This question was also very informative (similar question).
I'm trying to create a csv file from an excel file using MS Excel Interop in my C#/Winforms app.
Am getting this error on SaveAs method in the code below.
'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.'z
I tried setting readonly to false in Workbook's Open(...) method as per:
Problem saving excel file after inserting data , but still getting the same error.
In my code, the csv file path was:C:\
If I change the csv file path to C:\SomeFolder or some shared UNC path, then I dont get this error.
Please advise.COuld there be some permissions issues with C drive?
Heres the code:
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Visible = false;
wbkSrc = xlApp.Workbooks.Open(m_sSrcFil,
Type.Missing, false, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
wstSrc = (Worksheet)wbkSrc.Worksheets[sSrcSht];
//wstSrc.Activate();
rngWork = wstSrc.Cells.get_Range("H:H", System.Reflection.Missing.Value);
rngWork.NumberFormat = "General";
dteTmpDate = Convert.ToDateTime(m_sBusDate);
sTmpFileName = m_sSrcFil.Substring(0, m_sSrcFil.IndexOf(".")) + "_" +
m_sUserName + "_" + dteTmpDate.ToString("yyyy_MM_dd") + ".Csv";
wstSrc.SaveAs(sTmpFileName, XlFileFormat.xlCSV, Type.Missing,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Clearly sTmpFileName is an invalid path. The error message tells you that. Perhaps m_sUserName contains characters that are not allowed. Perhaps it is a DOMAIN\USER format user name. Perhaps the file name really is too long. Or perhaps something else is up. Take a look at the actual value of sTmpFileName and you will have your explanation.
As an aside, your code is mistaken in using SubString and IndexOf(".") to get the filename without the extension. Filenames can have multiple periods in them. The extension is simply that text after the final period. Consider these file names and how your code will deal with them:
C:\My.Folder.Name\TheFile.xls
C:\MyFolder\TheFile.Name.xls
Instead you should use Path.GetFileNameWithoutExtension.
Excel SaveAs is quite picky. Things like c:\folder\\file.csv (note the double backslash) are accepted by File.Exists or when you open a workbook, but not when saving
Check your FilePath where you are saving if it is more than 218 characters then also you will get this error.