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);
}
}
}
Related
I am using the following code to generate an Excel .xlsx file from a C# WinForms application using Microsoft.Office.Interop.Excel
As of now, the code simply creates a blank Excel file.
When I try to open the xlsx file, I get the following error. But if I rename the file extension to .xls, the file opens file.
void WriteData(DataSet ds, string excelFilePath)
{
Excel.ApplicationClass appExcel = null;
Excel.Workbooks workbooks = null;
Excel.Sheets workSheets = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Workbook wbTemplate = null;
Excel.Range range = null;
try
{
appExcel = new Excel.ApplicationClass();
ExcelUtils.InitExcel(appExcel);
workbooks = appExcel.Workbooks;
wb = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
wb.SaveAs(excelFilePath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
wb.Close(Type.Missing, Type.Missing, Type.Missing);
}
finally
{
ExcelUtils.CleanupExcel(appExcel, workbooks, workSheets, wb, ws);
appExcel = null;
}
}
I have read other similar questions but most of them are in other languages or using some Excel library. I need solution using Excel Interop. I do not want to save in OpenXML format.
You're using the wrong XlFileFormat member for the format you want when you save the file.
According the documentation:
xlWorkbookNormal is for *.xls files.
xlWorkbookDefault is for *.xlsx files.
Pass Excel.XlFileFormat.xlWorkbookDefault instead.
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'm working with Excel sheet of .xls format and writing data into it. The problem is that whenever the data doesn't start with alphabets it is prompting me different errors.
For example: When my column data started with =?us-ascii?Q?Google Keywords?= it threw me an exception:
Exception from HRESULT: 0x800A03EC
and when my data is like -------- Original Message --------Subject: the error was:
Not enough storage is available to complete this operation. (Exception from HRESULT: 0x8007000E (E_OUTOFMEMORY))
This is how I'm writing data:
foreach (AllCasesReplies infoList in allCasesReplies)
{
n = 0;
mWorkSheet.Cells[l + m, ++n] = infoList.id;
mWorkSheet.Cells[l + m, ++n] = infoList.replies;
m++;
}
This is how I clean my objects:
private static void SaveAndCollecttheGarbage(Microsoft.Office.Interop.Excel.Application excelApp, string path, Microsoft.Office.Interop.Excel.Sheets sheet)
{
excelApp.Columns.AutoFit();
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close(true, Missing.Value, Missing.Value);
sheet = null;
mWorkBook = null;
excelApplication.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
So I have tried omitting these data and they are working great.
Are there any rules that the column has to start with specific characters and if so, what are these?
if you type "?" in excel cell that has general format, the excel automaticall interprete that as a formula. You need to change the cell format before inserting the text into the cell.
something like:
foreach (AllCasesReplies infoList in allCasesReplies)
{
n = 0;
Microsoft.Office.Interop.Excel.Range range1 = mWorkSheet.Cells[l + m, ++n] as Range;
range1.NumberFormat = "#";
range1.Value2 = infoList.id;
Microsoft.Office.Interop.Excel.Range range2 = mWorkSheet.Cells[l + m, ++n] as Range;
range2.NumberFormat = "#";
range2.Value2 = infoList.replies;
m++;
}
i have 2 issues what i am facing
i have an dataset where i need to send the data from dataset to an
excel once data in dumped in that location.
i need to change the column headers make them bold
2:
Above the report headers we should pass 1 parameter that will be the name(Employee details) from c# we need to pass as an parameter to it.
it can change what ever parameter we pass it on.
ex:
Reportname: Employee details
Name EmpID city
Arun 11 bangalore
Kiran 56 chennai
Rahul 23 pune
The following should work, but I did not test it. Thank you to Deborah Kurata for writing a large part of the code below.
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
private void ExportToExcel(DataTable Table, string ReportName, string Filename)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet ;
oSheet.Name = "Report";
int rowCount = 3;
foreach (DataRow dr in Table.Rows)
{
for (int i = 1; i < Table.Columns.Count+1; i++)
{
// Add the header the first time through
if (rowCount==3)
{
oSheet.Cells[1, i] = Table.Columns[i - 1].ColumnName;
rowCount++;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
rowCount++;
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[3, 1],
oSheet.Cells[rowCount, Table.Columns.Count]);
oRange.EntireColumn.AutoFit();
// Set report title *after* we adjust column widths
oSheet.Cells[1,1] = ReportName;
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(Filename, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
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#