I have a DataTable
used to create a Worksheet with Interop
. Once I have the Worksheet I want to iterate over this Worksheet to get some cells that meets a condition and input there a new value.
For example, the next table is my Worksheet, once it is created I want to iterate over the worksheet and try to get only the values that are in red cells ... So the cells have to meet a condition.
How could I get these values, using SQL
or Interop
have some method to do this?
You can use the following code to get the values that are in red cells.
using Excel = Microsoft.Office.Interop.Excel;
static void Main(string[] args)
{
string pathToExcelFile = @"D:\test.xlsx";
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(pathToExcelFile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel._Worksheet sheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range ran = sheet.UsedRange;
for (int x = 1; x <= ran.Rows.Count; x++)
{
for (int y = 1; y <= ran.Columns.Count; y++)
{
var CellColor = sheet.UsedRange.Cells[x, y].Interior.Color;
if(CellColor==GetCustomColor(Color.Red))
{
string value = sheet.Cells[x, y].value.ToString();
Console.WriteLine(value);
}
}
}
Console.ReadKey();
}
private static Double GetCustomColor(Color color)
{
int nColor = color.ToArgb();
int blue = nColor & 255;
int green = nColor >> 8 & 255;
int red = nColor >> 16 & 255;
return Convert.ToDouble(blue << 16 | green << 8 | red);
}
Excel file:
Result:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.