C# 使用interop C在excel工作表上迭代#
我有一个C# 使用interop C在excel工作表上迭代#,c#,excel,visual-studio,interop,C#,Excel,Visual Studio,Interop,我有一个DataTable用于创建具有Interop的工作表。一旦我有了工作表,我想迭代这个工作表,得到一些满足条件的单元格,并在那里输入一个新值 例如,下一个表是我的工作表,创建后,我想在工作表上迭代,并尝试仅获取红细胞中的值。。。所以细胞必须满足一个条件 如何使用SQL或Interop获取这些值?您可以使用以下代码获取红细胞中的值 using Excel = Microsoft.Office.Interop.Excel; static void Main(string[] args)
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=Microsoft.Office.Interop.Excel;
静态void Main(字符串[]参数)
{
字符串pathToExcelFile=@“D:\test.xlsx”;
Excel.Application xlApp=新的Excel.Application();
Excel.Workbook xlWorkbook=xlApp.Workbooks.Open(路径为ExcelFile,0,true,5,“,”,true,Excel.XlPlatform.xlWindows,“\t”,false,false,0,true,1,0);
Excel._工作表=(Excel._工作表)xlWorkbook.Sheets[1];
Excel.Range ran=sheet.UsedRange;
对于(int x=1;x 8&255;
int red=nColor>>16&255;
返回Convert.ToDouble(蓝色),我建议您使用OpenXMLSDK阅读excel。互操作已经有十年历史了。