2009-02-05 65 views
0

我想阅读一些excel文件并将其转换为我自己的excel模板。我想阅读B coloumn每行。(B1,B2,B3 ...正在这样做。) 如果这个色号中有一个数字,在B3中有数字像“1,2,3,4,5,6,7,8,9”比我会得到这整行,并将其数组[i]。如果有“5”数字在B4比它会得到这整行,并把它给一个数组[i]。如果相关行中没有数字,它将contiune到下一行。它将contiune读取excel文件的结尾。我想要这个数组并写入一个新的Excel文件。这就是我想要的,请帮助我的示例代码。从Excel文件中读取特定的Coloumns用C#

+0

这是Office 2003以及更早或Office 2007? – hova 2009-02-05 18:47:11

回答

3
  1. Download并在计算机上安装Office 2003的主互操作程序集
  2. 创建一个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); 
} 
+0

我会尝试这一点。但这不是控制如果B1 B2 B3 ....是数字或Null ..如果它们为空或不是数字,它会得到下一行。如果你想我可以发送我的模板excel文件和非编辑的excel文件。 – 2009-02-06 12:27:18