Excel Read Value with Formulas to Lookup Failing - c#

Workbook SourceFile = oXLSrc.Workbooks.Open(Path.GetFileName(fileName), true);
TestSheet.get_Range("E33", Type.Missing);
The Sheet have a value and it's a ComboBox and data validation. This ComboBox values are coming from another worksheet. When I open the Excel in C#, ALL values are NULL. But when I open it in regular Excel it's working well and data is there. What am I missing?

Just based on your code above, you're not assigning the result of get_Range() to a variable. I expect to see something like...
private Workbook m_Workbook; // The currently opened Excel file
...
dynamic cellValue;
Worksheet sheet = null;
try
{
sheet = (Worksheet)m_Workbook.Worksheets[0];
cellValue = sheet.get_Range("E33").Value2;
}
catch (Exception e)
{
...
Data validation or comboboxes should not factor into this.
For information on Text vs Value vs Value2, see https://fastexcel.wordpress.com/2011/11/30/text-vs-value-vs-value2-slow-text-and-how-to-avoid-it/

Related

How to read data from Excel which is open and getting updated every seconds using C# ASP.NET?

I am using Office.Interop.Excel to read data from Excel using C# ASP.Net & Dotnet 6.
I can read the Data and everything seems to be working fine.
But I have a challenge here.
The excel which I am reading data from would be updated every second.
But I am seeing an error while trying to open it and update random data.
The error says that the file is locked for editing.
Please have a look at the code below:
public double GetGoldPrice()
{
string filename = #"D:\Test.xlsx";
int row = 1;
int column = 1;
Application excelApplication = new Application();
Workbook excelWorkBook = excelApplication.Workbooks.Open(filename);
string workbookName = excelWorkBook.Name;
int worksheetcount = excelWorkBook.Worksheets.Count;
if (worksheetcount > 0)
{
Worksheet worksheet = (Worksheet)excelWorkBook.Worksheets[1];
string firstworksheetname = worksheet.Name;
var data = ((Microsoft.Office.Interop.Excel.Range) worksheet.Cells[row, column]).Value;
excelApplication.Quit();
return data;
}
else
{
Console.WriteLine("No worksheets available");
excelApplication.Quit();
return 0;
}
}
My end goal is to get live data from Excel whenever I fire the function.
The Excel would be open and can be editing any time.
Please help!
You said your file is xlsx so you would be better not using Interop but Open XML SDK 2.5. Then you can open the file in read only mode:
using (SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(fileName, false))
{
// Code removed here.
}
Check here to get familiar with Open XML SDK

How to get alt text of a table in a excel worksheet

How to get alt text of a table in a excel worksheet?
I have this code to open a Excel Workbook, but how do I get the Alternative Text of a table in a woorksheet?
string filePath = #"C:\Temp\ExcelTable.xlsx";
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excel_wbk = excelApp.Workbooks.Open(filePath);
// This work if there is a shape in Worksheet 1:
string altTextShape = excel_wbk.Worksheets[1].Shapes[1].AlternativeText
// Code to get excel table alt text?
// excel_wbk.Worksheets[1].Tables[1].AlternativeText
// or excel_wbk.Worksheets[1].Table[1].AlternativeText doesn't exist
excelApp.Quit();
Alternative text doesn't exist on tables, check out this link and you'll see that alternative text is available for pivot tables and shapes and not much else.

how to detect an empty worksheet

I am attempting to use the ExcelWriter class to read the contents of an uploaded Excel file in a way where the code will process the data in any of the workbook's worksheets.
So something like this:
foreach (var worksheet in workbook.Worksheets)
{
var area = worksheet.PopulatedCells;
if (area == null)
break;
...do stuff with the cells in the area...
}
The problem is that when I call Worksheet.PopulatedCells I get an exception thrown saying that there aren't any populated cells when the worksheet is empty rather than returning me null.
Is there some way to detect if a Worksheet is empty?

How to set active sheet with Open XML SDK 2.5

using the example here How to Copy a Worksheet within a Workbook
I have successfully been able to clone/copy sheets in my excel file, however when I open the excel the 2nd sheet is the active(visible) sheet. I haven't been able to locate a property that could do thins.....Is there any way to specify what sheet is active?
I've tried to force it by opening and editing the first sheet in the file thinking it was the last edited sheet that was active but that didn't work either.
any help would be great. TIA
update: looking at the workbook.xml created when renaming the .xlsx to .zip I came accross the 'activeTab' property. made a quick change to my code and seems to work just fine
public void SetFirstSheetInFocus(String xlsxFile)
{
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(xlsxFile, true))
{
//Get a reference to access the main Workbook part, which contains all references
WorkbookPart _workbookPart = spreadSheet.WorkbookPart;
if (_workbookPart != null)
{
WorkbookView _workbookView = spreadSheet.WorkbookPart.Workbook.BookViews.ChildElements.First<WorkbookView>();
if (_workbookView != null)
{
_workbookView.ActiveTab = 0; // 0 for first or whatever tab you want to use
}
// Save the workbook.
_workbookPart.Workbook.Save();
}
}
}
If the name of your sheet is in the variable
sheetName
you can set the sheet with that name active like this:
using (var spreadsheetDoc = SpreadsheetDocument.Open(emptyHIPTemplatePath, true /* isEditable */, new OpenSettings { AutoSave = false }))
{
var workbookPart = spreadsheetDoc.WorkbookPart;
var workBook = spreadsheetDoc.WorkbookPart.Workbook;
var sheet = workBook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
var sheetIndex = workBook.Descendants<Sheet>().ToList().IndexOf(sheet);
var workBookView = workBook.Descendants<WorkbookView>().First();
workBookView.ActiveTab = Convert.ToUInt32(sheetIndex);
...
workBook.Save();
}
From Vincent Tan's book:
The SheetId property doesn't determine the order. The order of
appending the Sheet classes to the Sheets class, does.
When you add a sheet, it gets the next index, but a single sheet does not have an index. OpenXML gives it an index when you are done adding sheets. Again, from Vincent Tan's book:
Let's say you have 3 worksheets named Sheet1, Sheet2 and Sheet3.
However, when you appended the corresponding Sheet classes, you did it
as Sheet2, Sheet3 and Sheet1, in that order.

excel cell coloring

I am using c# to color particular cells of excel file.
i am using
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(destPath);
Worksheet ws = wb.Worksheets[1];
ws.Cells[row, clmn].Interior.Color = XlRgbColor.rgbBlack;
to color cells..But this is not working..
It is giving an exception on the last line where i am coloring the cells
"Exception from HRESULT: 0x800A03EC"
I am unable to fix the exception
Can anyone help me out..
It might not work because the worksheet is protected.
You can check it the following way:
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(destPath);
Worksheet ws = wb.Worksheets[1];
bool wasProtected = ws.ProtectContents;
if (wasProtected == true)
{
// unprotect the worksheet
}
else
{
ws.Cells[row, clmn].Interior.Color = XlRgbColor.rgbBlack;
}
...
if (wasProtected == true)
{
// protect back the worksheet
}
In my previous project I used the following snippet to Color Cells in Excel:
ws.Cells[row, clmn].Interior.Color = System.Drawing.ColorTranslator.ToWin32(Color.Black);
I tested the code that you have on a new Excel file and it works fine. However, I was able to reproduce the error when testing with a row value of 0. So maybe the problem is with the row and clmn values. Otherwise it must be something specific to your Excel file... maybe a protected cell or something along those lines.

Categories