且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#删除excel中突出显示的行和列

更新时间:2023-11-04 16:36:16





我认为你想要的代码看起来像下面的代码,尝试通过创建一个带有一些使用过的单元格的Test.xlsx excel文件来测试控制台应用程序中的代码(比如将第一行弄脏并插入字母或数字)然后制作背面颜色为黑色。只是不要忘记在项目中引用Microsoft.Office.Interop.Excel。请记住,你需要一个更好的异常处理和SOLID实现,下面的代码只是你最后工作的一个小指示。



 static void Main(string [] args)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
xlApp = new Excel.Application();
尝试
{
xlWorkBook = xlApp.Workbooks.Open(@C:\Test \ Test.xlsx);
xlWorkSheet =(Excel.Worksheet)xlWorkBook.Sheets [1];
var rows = xlWorkSheet.UsedRange;
foreach(行中的Excel.Range行)
{
double color = row.Interior.Color;
if(color == 0)// 0表示黑色
row.Delete();
}

xlWorkBook.Save();
xlWorkBook.Close();
}
catch(例外)
{
throw;
}
最后
{
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
}





干杯,

--AH。


Hello everyone,

I am having a excel sheet with highlighted rows and columns . Need to remove those highlighted color rows and columns and import into datatable in c#

What I have tried:

I am having a excel sheet with highlighted rows and columns . Need to remove those highlighted color rows and columns and import into datatable in c#

Hi,

I think your desired code will look like to the below one, try to test the code in console application by creating a Test.xlsx excel file with some used cells (like make the first rows dirty with inserting letters or numbers into them) then make the back color black. Just do not forget to reference Microsoft.Office.Interop.Excel in your project. Keep in your mind you need a better exception handling and also SOLID implementation the below code is only a small indication of your final work.

static void Main(string[] args)
		{
			Excel.Application xlApp;
			Excel.Workbook xlWorkBook;
			Excel.Worksheet xlWorkSheet;
			xlApp = new Excel.Application();
			try
			{
				xlWorkBook = xlApp.Workbooks.Open(@"C:\Test\Test.xlsx");
				xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
				var rows = xlWorkSheet.UsedRange;
				foreach (Excel.Range row in rows)
				{
					double color = row.Interior.Color;
					if (color == 0) // 0 indicates black color
						row.Delete();
				}

				xlWorkBook.Save();
				xlWorkBook.Close();
			}
			catch (Exception)
			{
				throw;
			}
			finally
			{
				xlApp.Quit();
				Marshal.ReleaseComObject(xlApp);
			}
		}



Cheers,
--AH.