I'm trying to read in the values of the first column into an array. What's the best way to do that? Below is the code I have so far. Basically I'm trying to get the range of data for that column so I can pull the cell values into a system array.
Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();
if (xlsApp == null)
{
Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
return null;
}
//xlsApp.Visible = true;
Workbook wb = xlsApp.Workbooks.Open(filename, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = wb.Worksheets;
Worksheet ws = (Worksheet)sheets.get_Item(1);
//***Breaks Here***
ListColumn column = ws.ListObjects[1].ListColumns[1];
Range range = column.DataBodyRange;
System.Array myvalues = (System.Array)range.Cells.Value;
Here is what I ended up using to get it to work. Once you know that Columns actually returns a range, storing it that way seems to compile and run fine. Here is the working method in my ExcelReader class. I plan to use this for test driven data on WebDriver.
public static string[] FirstColumn(string filename)
{
Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();
if (xlsApp == null)
{
Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
return null;
}
//Displays Excel so you can see what is happening
//xlsApp.Visible = true;
Workbook wb = xlsApp.Workbooks.Open(filename,
0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = wb.Worksheets;
Worksheet ws = (Worksheet)sheets.get_Item(1);
Range firstColumn = ws.UsedRange.Columns[1];
System.Array myvalues = (System.Array)firstColumn.Cells.Value;
string[] strArray = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();
return strArray;
}
First, I'd work out how many rows are actually being used:
Excel.Range allCellsInColumn = xlWorksheet.Range["A:A"];
Excel.Range usedCells = allCellsInColumn.Find("*", Missing.Value, Missing.Value, Missing.Value,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, Missing.Value, Missing.Value);
Once you have that you can retrieve the values:
System.Array values = usedCells.Values;
Once you have the values in the array you can skip over the elements with nothing in them. I don't think there is a way of retrieving just the cells with something in them without looping through them one at a time, which is very time consuming in Interop.
Is your data in a list? Your code seems to be looking for an Excel List which may not be present. If not you can just get the entire first column (A:A) into a Range and get it's Value:
Range firstCol = ws.Range("A:A");
System.Array values = range.Value as System.Array;
Related
I'm new to C#. I have used the code below to read data from Excel, but I need help modifying it to read key-value pairs.
public String getData(int row, int col, String var)
{
Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
List<string> prop = new List<string>(var.Split(new string[] {"."}, StringSplitOptions.None));
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(#"D:\\test.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[prop[0]];
excelWorksheet.Select(Type.Missing);
Excel.Range range = (excelWorksheet.Cells[row, col] as Excel.Range);
string cellValue = range.Value.ToString();
excelWorkbook.Close();
excelApp.Quit();
return cellValue;
}
return null;
}
Here is an example; it assumes you have a using clause..
using Excel = Microsoft.Office.Interop.Excel;
..and prepared access to a worksheet:
Excel.Application xl = new Excel.Application();
xl.Workbooks.Open(filename);
Excel.Worksheet ws = xl.Workbooks[1].Worksheets[1]; // pick your sheet!
int keyColum = 3;
Now you can grab a Range of Cells:
Excel.Range keyRange= ws.Range["C3:C53"];
..or the whole column:
Excel.Range keyRange= ws.Range["C:C"];
And search all occurences of a search string:
Excel.Range keysFound = keyRange.Find(textBox1.Text);
Then you can access the range of found cells like this:
string msg1 = keysFound.Count + " records found.";
string msg2 = "1st in row " + keysFound.Row;
string msg3 = "value from next column is "
+ ws.Cells[keysFound.Row + 1, keyColum + 1].value;
notes:
indexing start with 0 in c# but not in excel (hence [keysFound.Row + 1, )
my value column is one column right of the keys. Best use named indices!
if nothing is found keysFound will be null! (do add a check!)
since you want to match a whole key, you will want to do an exact search:
Excel.Range keysFound = keyRange.Find(textBox1.Text, LookAt: Excel.XlLookAt.xlWhole);
I still think grabbing all data and stuffing them into a Dictionary will be the cleanest and fastest solution, unless, that is you only need to do one lookup..
I have the below code which works to delete the first row of a specified excel workbook. After this is done I would like to save (Overwrite changes) and exit the excel applications.
I gathered this may be achieved by Workbook.Close(True) but the popups still occur and the Object workbook is not referenced.
Any help would be much appreciated.
public void DeleteRows(string workbookPath)
{
// New Excel Application
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Open WorkBook
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet);
Microsoft.Office.Interop.Excel.Range excelCell = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A1", "A1");
Microsoft.Office.Interop.Excel.Range row = excelCell.EntireRow;
row.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
}
Honestly, all I think that's missing from your code is a save and close. Once you save, the warning should not be issued.
using Excelx = Microsoft.Office.Interop.Excel;
public void DeleteRows(string workbookPath)
{
// New Excel Application
Excelx.Application excelApp = new Excelx.Application();
//Open WorkBook
Excelx.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excelx.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Excelx.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Excelx.Worksheet excelWorksheet = (Excelx.Worksheet)excelSheets.get_Item(currentSheet);
Excelx.Range excelCell = (Excelx.Range)excelWorksheet.get_Range("A1", "A1");
Excelx.Range row = excelCell.EntireRow;
row.Delete(Excelx.XlDirection.xlUp);
// This should be all you need:
excelWorkbook.Save();
excelWorkbook.Close();
}
I'd be puzzled if this doesn't work, but if it doesn't, it might help when you are debugging to make Excel visible and step through the code:
excelApp.Visible = true;
As a final last attempt, before you save, you can disable warnings which will tell Excel to dispense with any of the dialogs to try to save you from yourself:
excelApp.DisplayAlerts = false;
excelWorkbook.Save();
excelWorkbook.Close();
excelApp.DisplayAlerts = true;
And again, I think you shouldn't even get to step 2 for this to work, but let me know if it doesn't. We would have quite a puzzle.
I have been using the "Code Project" and "Stackoverflow" to create a script which will delete the first row of a specified excel workbook.
I am having an issue with line 13 "Range.EntireRow;" with the error "An object reference is required for the non-static field, method, or property Range.Entire.Row
Please see the script I have created below;
public void DeleteRows(string workbookPath)
{
// New Excel Application
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Open WorkBook
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet);
Microsoft.Office.Interop.Excel.Range excelCell = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A1", "A1");
Microsoft.Office.Interop.Excel.Range row = Range.EntireRow; //ERROR Line
row.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
Any advice on how to fix this error would be greatly appreciated.
You could refer to the Cells of the Range to get the entire row:
Microsoft.Office.Interop.Excel.Range row = excelCell.Cells.EntireRow
or even omitting the Cells should work as well:
Microsoft.Office.Interop.Excel.Range row = excelCell.EntireRow
MSDN Range.EntireRow Property
You should use: Microsoft.Office.Interop.Excel.Range row = excelCell.EntireRow;
I want to append a data to a existing excel file using c#.I Tried it using below codes,but it is giving wrong column value after opening of the excel file(if my excel file contains 4 columns,but here it is returning column count as 1 only).
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0); //#"H:\TestFile.xlsx"
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets.get_Item(sheetNum);
rng = xlWorkSheet.UsedRange;
int colCount = rng.Columns.Count;
int rowCount = rng.Rows.Count;
rng = (Excel.Range)xlWorkSheet.Cells[rowCount, colCount];
Excel.Range newColumn = rng.EntireColumn;
xlWorkSheet.Cells[1, colCount + 3] = "Udupi";
xlWorkBook.Save();
xlWorkBook.Close(misValue, misValue, misValue);
xlApp.Quit();
How can i append a data to excel file?Is there any other methods are available to achieve this one!
Have you tried Epplus library for creating and editing Excel spreadsheets and workbooks in C#? I have worked on it before some weeks ago. It is super. I recommend to use it.
public bool StoreInExecel(String name,String csFIleName)
{
int cellno = ;//Initialize to current row no
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = (Microsoft.Office.Interop.Excel.Workbook)excelApp.Workbooks.Add(Missing.Value);
Worksheet worksheet;
// Opening excel file
workbook = excelApp.Workbooks.Open(fileName, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Get first Worksheet
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);
// Setting cell values
((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[cellno,"B"]).Value2 = "5";
((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[cellno,"B"]).Value2 = "7";
workbook.Save();
workbook.Close(0, 0, 0);
//excelApp.Quit();
return true;
}
I want to initialize "cellno" to current row index of excel file so that data should not get overridden. Is there any specific function to get filled row count?
You can use
Excel.Range range = (Excel.Range)excelApp.ActiveCell;
int cellno = range.Row;
You can also get the used range in a worksheet using the UsedRange property.