I am on a winform application which performs operations with excel files.
Now i have got an issue that i need to get first unused rows occured before a used row(edited row).
I have used the below code and which gives only the usedrange.
string fileName = Directory.GetCurrentDirectory()+"\\123.xlsx";
Excel.Application xlApp;
Excel.Workbook xlWorkbook;
xlApp = new Excel.Application();
xlWorkbook = xlApp.Workbooks.Open(fileName);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlApp.Workbooks[1].Worksheets[1];
Excel.Range excelCell = xlWorksheet.UsedRange;
Object[,] values = (Object[,])excelCell.Value2;
int rows = values.GetLength(0);
int cols = values.GetLength(1);
Exmlple:
From the above example i need to get the result as '3' Cols and '10' rows.
Now its '3'Cols and '7'rows.
Please help me if there is any idea for this. Thank You.
Quick and dirty - you could use something like the following:
int rows = excelCell.Rows.Count + excelCell.Row - 1;
And something similar for columns.
Related
How do I copy an Array to an Excel Range in C#?
Why does the below code not work?
If I assign it like this, then in each cell is the same value
Workbook workbook;
Worksheet worksheet;
List<double> flow = new List<double>();
workbook = excel.Workbooks.Open(filename);
worksheet = workbook.Worksheets.Add();
worksheet.Range[$"$A$1:$A{flow.count}"].Value = flow.ToArray();
Of course the list is filled with values. I have omitted this part here.
replace your last line with
Excel.Range range = sheetSource.UsedRange.Columns[columnIndx];
range.Value = application.WorksheetFunction.Transpose(flow.ToArray());
Hi I have an excel file settings.xlsx. I want to read the data from this file and assign the variables used in my code with the data.
example
Column1 Column2
Row1 Data 500
Row2 Address 30
Row3 Value FPGA
I have Data,Address and Value as variables in my code.
Can someone assist me with a pseudocode of c# to open a file and read the contents from it as per my requirement?
I want to search "Data" word in the excel file and take the value next to the cell containing "Data" and assign it to the variable "Data". I know it is confusing but I really want the final data to look like something below.
Data=500 //Finally I want my variables to have the data as follows
Address=30
Value= FPGA
I tried opening a file in my code.But since I am new to c#,i am not able to understand what is going wrong in my code.
I am stuck at this point. Open function is giving an error. Kindly help me. I tried to open the excel file in my c# code. But somehow it is saying Open function overload method doesn't take one argument. How to open and read the file?
string Filepath = #Filename;
Excel.Application excelapp = new Excel.Application();
excelapp.Visible = true;
var MyBook = excelapp.Workbooks.Open(Filepath);
It will be really helpful if somone gives a pseudocode for the same.
Hi,
I was able to open the file.
string Filepath = Path.Combine(Directory.GetCurrentDirectory(), Filename);
Excel.Application excelapp = new Excel.Application();
excelapp.Visible = true;
var Workbook = excelapp.Workbooks.Open(Filepath, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0,true,1, 0);
var xlWorkSheet = (Excel.Worksheet)Workbook.Worksheets.get_Item(2);
Excel.Range range = xlWorkSheet.UsedRange;
But when I try to store the cell value in my variable, it gives me an error. I somehow cannot use Cells.value. I tried using the following but not able to store the data. Can anybody help?
uint pbaudRate2 = Convert.ToUInt32(range.Value2.ToString());
If you can make a slight change in your excel file, there is a much easier way to read the data. You need to have Column names in the first row (any names will do e.g. "ColumnName", "ColumnValue"), and data in subsequent rows. Then you can use code like this:
string xlConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=yourfullfilepathandname.xlsx;Extended Properties='Excel 8.0;HDR=Yes;';";
var xlConn = new OleDbConnection(xlConnStr);
var da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", xlConn);
var xlDT = new DataTable();
da.Fill(xlDT);
You will now be able to access the values from the DataTable. In your case: xlDT.Rows[1][1] will hold the value of address (in this case 30). One thing to note: numbers in an Excel spreadsheet need to be retrieved as doubles and then cast if you want something else:
int myAddress = (int)(double)xlDT.Rows[1][1];
Here is a small demo how to read a range of Excel cells
// cf. http://support.microsoft.com/kb/302084/en-us
Excel.Application XL = new Microsoft.Office.Interop.Excel.Application();
Excel._Workbook WB = XL.Workbooks.Open(fileName, ReadOnly: true);
Excel._Worksheet WS = (Excel._Worksheet)WB.Sheets[sheetName];
Excel.Range R = WS.get_Range(GetAddress(row1, col1), GetAddress(row2, col2));
object[,] arr = (object[,])R.Value;
....
private string GetAddress(int rowNumber, int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName + rowNumber;
}
The cell values are copied to a 2D array of objects. Further processing depends on the value types.
Note that the transfer of an array is much faster than a nested loop of single cell copy operations.
I have a workbook that has roughly 32 worksheets in it, I am using C# to add a new worksheet, and it always adds the worksheet at the end, and I would like for the worksheet to be added as the 2nd worksheet. Is it possible to control the positioning of the added worksheet?
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.Add(System.Reflection.Missing.Value, xlWorkBook.Worksheets[xlWorkBook.Worksheets.Count], System.Reflection.Missing.Value, System.Reflection.Missing.Value);
xlWorkSheet.Name = "Added through code";
Worksheets.Add takes four parameters: Before, After, Count, and Type.
You're passing in the "After" parameter as the final worksheet, which is why it's being added at the end.
To add the new worksheet in a specific place, you have to specify where.
If you want it to be the second worksheet, pass the first worksheet as the "After" parameter:
xlWorkBook.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets[1], // worksheets are 1 based
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
Or you could it add it after a named worksheet:
xlWorkBook.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets["sheet1"],
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
I want to write from my form (in C#) to an excel spread sheet and delete certain rows if blank.
I can write perfectly fine to a speadsheet and save it, but lets say the user entered data into row a1, a2, a3, and a4, I now want to delete all the rows in between a4 and a29.
All I need is to find out how to delete a certain range of cells.
Thanks
// Here is the answers to
// 1. Delete entire row - Below rows will shift up
// 2. Delete few cells - Below cells will shift up
// 3. Clear few cells - No shifting
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultFilePath);
ExcelApp.Visible = true;
Excel.Worksheet ExcelWorksheet = ExcelWorkbook.Sheets[1];
Excel.Range TempRange = ExcelWorksheet.get_Range("H11", "J15");
// 1. To Delete Entire Row - below rows will shift up
TempRange.EntireRow.Delete(Type.Missing);
// 2. To Delete Cells - Below cells will shift up
TempRange.Cells.Delete(Type.Missing);
// 3. To clear Cells - No shifting
TempRange.Cells.Clear();
You can use this. İt's working ...
_Application docExcel = new Microsoft.Office.Interop.Excel.Application { Visible = false };
dynamic workbooksExcel = docExcel.Workbooks.Open(#"C:\Users\mahmut.efe\Desktop\Book4.xlsx");
var worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;
((Range)worksheetExcel.Rows[2, Missing.Value]).Delete(XlDeleteShiftDirection.xlShiftUp);
workbooksExcel.Save();
workbooksExcel.Close(false);
docExcel.Application.Quit();
For more information you can visit this web site
You can do it using a Range Object. I assume here that you are using Excel interop.
Let say you have your book open, then set the range then delete it
It should look something like this
ApplicationClass excel = new ApplicationClass();
//Abrir libro y seleccionar la hoja adecuada aqui
//...
Microsoft.Office.Interop.Excel.Range cel = (Range)excel.Cells[rowIndex, columnIndex];
cel.Delete();
You can specify a cell (eg. A1) and find the entire row containing that cell as a range and then can delete the row.
excel.Worksheet sheet = (excel.Worksheet)excelWorkBook.Sheets["sheet1"];
excel.Range cells = (excel.Range)sheet.Range["A1", Type.Missing];
excel.Range del = cells.EntireRow;
del.Delete();
The above given code will delete first row from sheet1
To remove a row you need an only simple row of code as a follow
xlWorkSheet.Rows[NUMBER_ROW].Delete();
using Microsoft.office.interop.excel delete rows using workseet range
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(srcFile);
Excel.Worksheet workSheet = xlWorkbook.Sheets[1];
Excel.Range range = workSheet.Rows[2];
range.Delete();
xlWorkbook.SaveAs(dstFile);
xlWorkbook.Close();
xlApp.Quit();
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.get_Range(ws.Cells[row, clmn]).Cells.Interior.Color = 36;
...to color cells, but this is not working.
Can anyone help me out?
Try something like that
ws.Cells[row, clmn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
Cells[row, clmn] is a range so you don't need to call get_Range() and there is a enum that you can use for colors.
ws.Cells[row, clmn].Interior.Color = XlRgbColor.rgbBlack;
If you want to set color by color index, you need to use this method:
Cells[row, col].Interior.ColorIndex = 36;
You can color a cell or a entire column or entire row.
The below code will help you out.
xlWorkSheet.get_Range(xlWorkSheet.Cells[2, 2], xlWorkSheet.Cells[2, 4]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
else
xlWorkSheet.get_Range(xlWorkSheet.Cells[2, 3], xlWorkSheet.Cells[2, 3]).Interior.Color = Excel.XlRgbColor.rgbRed;
Here xlWorksheet is the object excel Worksheet object.
get_Range takes 2 variable one start cell and other is end cell.
so if you specify both the values same then only one cell is colored.
xlWorkSheet.cells[row, column] is used to specify a cell.
System.Drawing.ColorTranslator.ToOle(SystemDrawing.Color.Green) is used to define the color in OLE format.
Excel.XlRgbColor.rgbRed is a excel way of coloring the cells
This method gives access to large number of colors which can be found here list of colors
The below code is the way i defined the excel worksheet.
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range xlwidthadjust; //used this to adjust width of columns
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
with this code i am sure that you wont get this exception Exception from HRESULT: 0x800A03EC
Make sure you are using:
using Excel = Microsoft.Office.Interop.Excel;
If you have a variable for the range you want to change, then use:
chartRange = xlWorkSheet.get_Range("a5", "a8");
chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
If you want to just change the color of a specific cell, then use:
xlWorkSheet.Cells[row, col].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
...where 'row' is the row number, and 'col' is the column number assigned to the given lettered columns (starting at 1).
Exception from HRESULT: 0x800A03EC
Solution: Change the misValue to sheet1, sheet2 or sheet3.
xlWorkBook = xlApp.Workbooks.Add("sheet1");
This works for me. system.reflaction.missing.value what was that, it is not related to Excel.workbooks.add came from a Excel file default value.
When you create a Excel file, the default worksheets are sheet1, sheet2 and sheet3.