使用C#从Excel文件中读取特定的Coloumns

我想读一些excel文件并转换成我自己的excel模板。我想每行都读一遍b。(B1,B2,B3 …是这样的。)如果在这个coloumn中有一个数字, 在B3中有数字如“1,2,3,4,5,6,7,8,9”比我会得到这个整行,并把它的数组[i]。如果有“5”数字在B4比它会得到这整个行,并把它的数组[i]。如果没有相关行中的数字将contiune到下一行。它将contiune读取excel文件的结尾。我想要这个数组并写入一个新的Excel文件。这就是我想请帮助我的例子代码。

  1. 在计算机上下载并安装Office 2003主互操作程序集
  2. 创build一个Visual Studio项目,并从GAC添加对“Microsoft.Office.Interop.Excel.dll”的引用。
  3. 现在你可以编写这个代码从任何Excelfile读取数据:

    using Excel = Microsoft.Office.Interop.Excel;

    string pathOfExcelFile = "C:\\MyDataFile.xls";

    Excel.Application excelApp = new Excel.Application();

    excelApp.DisplayAlerts = false; //Don't want Excel to display error messageboxes

    Excel.Workbook workbook = excelApp.Workbooks.Open(pathOfExcelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //This opens the file

    Excel.Worksheet sheet = workbook.get_Item(1); //Get the first sheet in the file Excel.Range bColumn = sheet.get_Range("B", null);

    List<string> dataItems = new List<string>();

    foreach (object o in bColumn)

      Excel.Range row = o as Excel.Range; string s = row.get_Value(null); dataItems.Add(s); 

    }