从Excel中读取interop并将不同的值写入另一个工作表

我正在使用C#4.0,并从一个Excel表中读取,并从每个列中获取值,然后在另一个表上,我正在写每列不同的值。

即如果结果表具有:

COLA COLB COLC ----- ------- ------- dog cow rabbit cat moose hare dog moose bunny bird yak hare fish fox bunny weasel fox bunny 

那么不同的表应该有(在每一列内sorting并不重要):

 COLA COLB COLC ----- ------- ------- dog cow rabbit cat moose hare bird yak weasel fish fox bunny 

任何人都可以提出一个更简单的方法(仍然使用COM Interop的Excel)否定需要使用这个丑恶的二维对象数组,ArrayList,列表回到array.etc。

这是我正在编写的代码,感觉就像我走错了方向:

 for (int c = 0; c < num_of_cols; c++) { string colref = NumToLetter(c + 1); int lastRow = workbook.Sheets["Results"].Cells[workbook.Sheets["Results"].Rows.Count, colref].End(MSExcel.XlDirection.xlUp).Row; MSExcel.Range excelRange = workbook.Sheets["Results"].Range[colref + "2:" + colref + lastRow]; object[,] valueArray = (object[,])excelRange.get_Value(MSExcel.XlRangeValueDataType.xlRangeValueDefault); List<ArrayList> distinctList = new List<ArrayList>(); for (int index = 0; index < num_of_cols.Length; index++) distinctList.Add(new ArrayList()); for (int i = 1; i <= valueArray.GetUpperBound(0); i++) { if (valueArray[i, 1] != null) { if (!distinctList[c].Contains(valueArray[i, 1].ToString())) distinctList[c].Add(valueArray[i, 1].ToString()); } } var startCell = (MSExcel.Range)distinctVals_worksheet.Cells[1, c + 1]; var endCell = (MSExcel.Range)distinctVals_worksheet.Cells[distinctList[c].Count,c + 1]; var writeRange = distinctVals_worksheet.Range[startCell, endCell]; writeRange.Value2 = distinctList[c].ToArray(); } 

我认为你可以做到这一点每列的基础上,并使用LINQselect不同的值,然后写在目标上。 像这样的东西:

 static IEnumerable<string> GetValuesOfColumn(this Excel.Sheet sheet,int col) { //returns all the values of the specific column of a sheet } static void WriteValuesToColumn(this Excel.Sheet sheet,IEnumerable<string> values,int col,int row) { //Writes values to a certain range of a sheet } 

那么你可以做这样的事情:

 var distinctValues=mySheet.GetValuesOfColumn(0).Distinct(); myOtherSheet.WriteValuesToColumn(distinctValues,0,0);