[英]Iterate over excel worksheet using interop C#
I have a DataTable
used to create a Worksheet with Interop
.我有一个
DataTable
用于创建带有Interop
的 Worksheet 。 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?我如何获得这些值,使用
SQL
或Interop
有一些方法可以做到这一点?
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: Excel文件:
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.