我有一个DataTable
,用于使用Interop
创建工作表。一旦有了工作表,我想遍历该工作表以获取一些满足条件的单元格并在其中输入新值。
例如,下一张表是我的工作表,创建后,我要遍历工作表并尝试仅获取红色单元格中的值 ...因此,单元格必须满足条件。
如何使用SQL
或Interop
获得这些值,有一些方法可以做到这一点?
您可以使用下面的代码来获取红色单元格中的值。
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文件:
结果: