I am using the below mentioned code for finding the row count of an Excel table but it seems there is something wrong since I am not getting the desired output. Please provide some solution to it.
The code is as follows:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = null;
Excel.Workbook wb = null;
Excel.Worksheet worksheet = null;
int lastUsedRow = 0;
string srcFile = #"Path to your XLSX file";
xlApp = new Excel.ApplicationClass();
xlApp.Visible = false;
wb = xlApp.Workbooks.Open(srcFile,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
worksheet = (Excel.Worksheet)wb.Worksheets[1];
Excel.Range range
// Find the last real row
lastUsedRow = worksheet.Cells.Find("*",System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious,
false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row;
xlApp.Workbooks.Close();
xlApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(xlApp);
You can try:
wb = xlApp.Workbooks.Open(srcFile,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
worksheet = (Excel.Worksheet)wb.Worksheets[1];
object[,] values = worksheet .UsedRange.Value2;
int rowCount = values.GetLength(0);
int colCount = values.GetLength(1);
i am trying to read the comments from excel sheet but unable to do so. Please help. Thanks in advance. my code is as follows-
Excel.Application appExl;
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(Server.MapPath("~/" + System.Configuration.ConfigurationManager.AppSettings["ExcelFile"] + fileName), Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
string obj = NwSheet.Range[0].Comment.Text;
You basically had it, but as Wimbo said, 0 isn't a valid range.
When interoping with Office from .Net, arrays always start at one. A range is a 2D array, so once you have a range, the top left cell in that Range is accessed like so:
using Excel = Microsoft.office.Interop.Excel;
Excel.Range range = worksheet.Cells[1,1];
To access the cell below the top left one, you would do this:
Excel.Range range = worksheet.Cells[2,1]; //It goes row, then column
To access the cell one to the right of the top left cell, you do this:
Excel.Range range = worksheet.Cells[1,2];
If you are working in .Net 4 or above, you don't need to specify the optional parameters (in otherwords you can drop all of the Missing.Value's). I'm guessing you want to get the comment in Cell A1 on Sheet 1 in a workbook, I would do this like so:
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelComments
{
class Program
{
static void Main()
{
var application = new Excel.Application();
var workbook = application.Workbooks.Open(#"C:\Yada yada\workbook with comments.xlsx");
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Range range = worksheet.Cells[1, 1];
//Here is your comment as a string
var myComment = range.Comment.Text();
workbook.Close(false);
application.Quit();
Marshal.ReleaseComObject(application);
}
}
}
I have a C# program that is creating, writing, and saving an excel file using the Excel Interop. The problem is that if I don't have the application quit immediately after saving and closing the excel file then the c# application gets an unhandled exception and crashes. Has anyone found a way to do this while being able to keep the host c# application open and running.
Here is the code that handles everything involving the Excel Interop
class CreateExcelDoc
{
string newFormString = trialReportForm.newFormString;
string fileString=trialReportForm.fileString;
int sheetCount;
string trialString = trialReportForm.trialString;
string dateString = trialReportForm.dateString;
string saveString = trialReportForm.saveSting;
System.Windows.Forms.Timer excelTimer = new System.Windows.Forms.Timer();
private Excel.Application app = null;
private Excel.Workbook workbook = null;
private Excel.Worksheet worksheet = null;
private Excel.Range workSheet_range = null;
public CreateExcelDoc()
{
createDoc();
}
public void createDoc()
{
try
{
app = new Excel.Application();
//app.Visible = false;
if (startForm.exportOwnerString == "Yes")
{
app.Visible = true;
startForm.exportOwnerString = " ";
}
else
{
app.Visible = false;
}
if (startForm.excelActionFlag=="addNewTrialReport")
{
workbook = (Excel.Workbook) app.Workbooks.Add(1);
//workbook.SaveAs(newFileForm.desktopPath + "\\" + "OB "+trialReportForm.otrClubNameString+" - "+trialReportForm.otrDateString);
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
//fileNameString = newFileForm.desktopPath + "\\OB " + trialReportForm.otrClubNameString + " " + trialReportForm.otrDateString;
workbook.Worksheets[1].Name = trialReportForm.trialReportDate+" Trial "+trialReportForm.trialReportTrialNumber;
}
else if (startForm.excelActionFlag == "ownerContacts")
{
workbook = (Excel.Workbook)app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = "Owner Contacts";
}
else if (startForm.excelActionFlag == "newExcelResults")
{
string testFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\test";
workbook = (Excel.Workbook)app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = "Event 1 Results";
//workbook.SaveAs(testFile, Missing.Value, Missing.Value, Missing.Value, false);
//workbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\Results", Missing.Value, Missing.Value, Missing.Value, false);
//workbook.SaveAs(startForm.excelFileLocation, Missing.Value, Missing.Value, Missing.Value, false);
//fileNameString = registrationForm.regFileLocation + "\\OB " + registrationForm.regClubName + " " + registrationForm.regDateString;
}
else if (dogForm.dogRegistrationExcel == "Yes")
{
workbook = (Excel.Workbook)app.Workbooks.Add(1);
workbook.SaveAs(dogForm.filePath, Missing.Value, Missing.Value, Missing.Value, false);
}
else if (newFormString == "No")
{
//workbook = app.Workbooks.Open(fileString, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
// workbook.Close(true,fileString,Missing.Value);
workbook = (Excel.Workbook)app.Workbooks.Open(fileString, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
if (newFormString=="Yes"®istrationForm.formString=="OTR")
{
//string sheetName = "Trial Report - " + dateString + " " + trialString;
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name =trialReportForm.otrDateString+" Trial " + trialReportForm.otrTrialString;
//workbook.Worksheets[1].Name = "Trial Report - " + dateString + " " + trialString;
//workbook.Worksheets[1].Name = "Hello";
//Excel.Name name1 = worksheet.Names.Add("Trial Report - " + dateString + " " + trialString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//worksheet.Name = "Trial Report - " + dateString + " " + trialString;
}
else if (newFormString == "Yes" & registrationForm.formString == "Registration")
{
//string sheetName = "Trial Report - " + dateString + " " + trialString;
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = "Results: "+registrationForm.selectedEvent;
//workbook.Worksheets[1].Name = "Trial Report - " + dateString + " " + trialString;
//workbook.Worksheets[1].Name = "Hello";
//Excel.Name name1 = worksheet.Names.Add("Trial Report - " + dateString + " " + trialString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//worksheet.Name = "Trial Report - " + dateString + " " + trialString;
}
else if (startForm.excelActionFlag == "addExistingTrialReport")
{
workbook = (Excel.Workbook)app.Workbooks.Open(startForm.excelFileLocation, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
sheetCount = workbook.Worksheets.Count;
int sheetCountPlusONe=sheetCount+1;
worksheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value,workbook.Worksheets[sheetCount],Missing.Value,Missing.Value);
workbook.Worksheets[sheetCountPlusONe].Name = trialReportForm.trialReportDate + " Trial " + trialReportForm.trialReportTrialNumber;
//worksheet.Move(Missing.Value, workbook.Worksheets[sheetCount]);
}
else if (startForm.excelActionFlag == "existingExcelResults")
{
workbook = (Excel.Workbook)app.Workbooks.Open(startForm.excelFileLocation, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
sheetCount = workbook.Worksheets.Count;
int sheetCountPlusONe = sheetCount + 1;
worksheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value, workbook.Worksheets[sheetCount], Missing.Value, Missing.Value);
workbook.Worksheets[sheetCountPlusONe].Name = "Event " + sheetCountPlusONe.ToString() + " Results";
//worksheet.Move(Missing.Value, workbook.Worksheets[sheetCount]);
}
else if (dogForm.dogRegistrationExcel == "Yes")
{
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = dogForm.dogUKCNumber;
}
}
catch (Exception e)
{
Console.Write("Error");
}
/* if (trialReportForm.saveMe=="Yes")
{
workbook.Save();
workbook.Close();
}
*/
}
public void createHeaders(int row, int col, string htext, string cell1,
string cell2, int mergeColumns, string b, bool font, int size, string
fcolor)
{
worksheet.Cells[row, col] = htext;
workSheet_range = worksheet.get_Range(cell1, cell2);
workSheet_range.Merge(mergeColumns);
switch (b)
{
case "BLUE":
workSheet_range.Interior.Color = System.Drawing.Color.Red.ToArgb();
break;
case "GAINSBORO":
workSheet_range.Interior.Color =
System.Drawing.Color.Gainsboro.ToArgb();
break;
//case "Turquoise":
// workSheet_range.Interior.Color =
//System.Drawing.Color.Turquoise.ToArgb();
//break;
case "PeachPuff":
workSheet_range.Interior.Color =
System.Drawing.Color.PeachPuff.ToArgb();
break;
default:
// workSheet_range.Interior.Color = System.Drawing.Color..ToArgb();
break;
}
//workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
//workSheet_range.Borders = null;
workSheet_range.Font.Bold = font;
workSheet_range.ColumnWidth = size;
//workSheet_range.HorizontalAlignment = ContentAlignment.BottomCenter;
if (startForm.excelActionFlag == "existingExcelResults" | startForm.excelActionFlag=="newExcelResults")
{
workSheet_range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
}
//workSheet_range.Cells.HorizontalAlignment = ContentAlignment.MiddleCenter;
workSheet_range.Font.Color = System.Drawing.Color.FloralWhite.ToArgb();
}
public void addData(int row, int col, string data,
string cell1, string cell2, string format)
{
worksheet.Cells[row, col] = data;
workSheet_range = worksheet.get_Range(cell1, cell2);
//workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
workSheet_range.NumberFormat = format;
workSheet_range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
excelTimer.Tick += new EventHandler(excelTimer_Tick);
excelTimer.Interval = 6000;
excelTimer.Start();
}
void excelTimer_Tick(object sender, EventArgs e)
{
if (startForm.excelActionFlag != "ownerContacts")
{
if (startForm.excelActionFlag == "existingExcelResults" | startForm.excelActionFlag == "newExcelResults")
{
/* Excel.Range sortRange;
sortRange = worksheet.get_Range("A14", "K32");
Excel.Range scoreColumn;
scoreColumn = worksheet.get_Range("C14", "C32");
sortRange.Sort(scoreColumn, Excel.XlSortOrder.xlDescending);*/
Excel.Range valueRange;
Excel.Range placeRange;
placeRange = worksheet.get_Range("A14", "A" + (14 + (registrationForm.numberofCompetitors - 1)).ToString());
valueRange = worksheet.get_Range("A14", "K"+(14+(registrationForm.numberofCompetitors-1)).ToString());
valueRange.Sort(valueRange.Columns[3, Type.Missing], Excel.XlSortOrder.xlDescending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
placeRange.Sort(placeRange.Columns[1, Type.Missing], Excel.XlSortOrder.xlAscending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
}
// workbook.Close(true, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Results.xls", Missing.Value);
workbook.Close(true, startForm.excelFileLocation, Missing.Value);
app.Quit();
Application.Exit();
/* workSheet_range = null;
worksheet = null;
workbook = null;
app = null;*/
//Thread.Sleep(5000);
// File.Move(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Results.xls", startForm.excelFileLocation);
}
}
}
I find that when saving with excel, I have more luck using the SaveAs method. For example:
private static Microsoft.Office.Interop.Excel.Application xlApp = null;
private static Microsoft.Office.Interop.Excel.Workbook xlWb = null;
private static Microsoft.Office.Interop.Excel.Worksheet xlWs = null;
//Your code and operations
xlWb.SaveAs(filePath, XlFileFormat.xlExcel8, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xlApp.Quit();
Marshal.ReleaseComObject(xlWs);
Marshal.ReleaseComObject(xlWb);
Marshal.ReleaseComObject(xlApp);
Several solutions including mine are presented How do I properly clean up Excel interop objects?
You can choose among the most sever (Killing Excel process) to more tender solutions (releasing COM object)
void excelsave()
{
try
{
ApplicationClass app = new ApplicationClass(); // the Excel application.
Workbook book = null;
Worksheet sheet = null;
Range range = null;
// the range object is used to hold the data
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
string execPath =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
book = app.Workbooks.Open(#"E:\SSIS\ABC\Book1.xls",
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
sheet = (Worksheet)book.Worksheets[1];
range = sheet.get_Range("A1", Missing.Value);
range.Columns.ColumnWidth = 22.34;
range = sheet.get_Range("B1", Missing.Value);
range.Columns.ColumnWidth = 22.34;
book.SaveAs(#"E:\SSIS\ABC\Book1.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
}
}
Here I am opening an excel sheet trying to increase the column width and need to make the column headers as bold and save the document, right now the document is not getting saved. I am using vs 2008, c# 3.5
Is There anything that I am doing wrong here? any help on this would be great
looking an for solution
I ran the following using VS 2010 and .NET 4, but this code should still work in your environment. Also, I simplified your code a bit. Hopefully this will get you going in the right direction.
static void excelsave()
{
try
{
Application app = new Application();
string execPath =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Workbook book = app.Workbooks.Open(#"c:\test.xls");
Worksheet sheet = (Worksheet)book.Worksheets[1];
Range range = sheet.get_Range("A1");
range.Columns.ColumnWidth = 22.34;
range = sheet.get_Range("B1");
range.Columns.ColumnWidth = 22.34;
sheet.get_Range("A1", "B1").Font.Bold = true;
book.SaveAs(#"c:\test2.xls"); // or book.Save();
book.Close();
}
catch (Exception ex)
{
}
}
UPDATE
You can find a similar explanation/example of what you are doing at:
http://www.dotnetperls.com/excel
Marshal.ReleaseComObject(book); // do this after the close
Also, there is a good discussion on cleaning up Excel/COM ...
How To Properly Clean Up Excel Interop Objects In c#
I copy worksheets from one workbook and paste them into a second workbook.
I use this code:
book = appExcel.Workbooks.Open(#"e:\tr\pliki\filename.xlsm",
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
Microsoft.Office.Interop.Excel.Global global = new Microsoft.Office.Interop.Excel.GlobalClass();
sheet.Copy(Missing.Value, global.Sheets[5]);
book.Save();
All works fine, but the problem is with the formulas. After worksheet has been copied formulas in it refer to values in the first workbook. The formulas paths contains paths to first workbook from which its was copied:
='E:\tr\pliki\[filename.xlsm]worksheetA'!A1:E2
and should be like this:
='worksheet'!A1:E2
Does anyone help me ?
I'm not aware of a clean way to do what your trying to do, anyway this is a workaround that could solve your problem. It's simply a matter of changing formulas to text before copying the worksheet and restore everything after that. I.e. you can replace all the = in your cells with some string which you know is not present in your data (e.g. something weird like X_X_X_X_X_X) and then revert to the initial situation.
The code could be something like this:
Microsoft.Office.Interop.Excel.Application appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook srcBook = appExcel.Workbooks.Open(#"c:\tmp\test.xls",
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
Microsoft.Office.Interop.Excel.Workbook destBook = appExcel.Workbooks.Add(Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet srcSheet = (Microsoft.Office.Interop.Excel.Worksheet)srcBook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range usedRange = srcSheet.UsedRange;
usedRange.Replace("=", "X_X_X_X_X_X", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
srcSheet.Copy(destBook.Worksheets[1], Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet destSheet = (Microsoft.Office.Interop.Excel.Worksheet)destBook.Worksheets[1];
usedRange.Replace("X_X_X_X_X_X", "=", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
usedRange = destSheet.UsedRange;
usedRange.Replace("X_X_X_X_X_X", "=", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);