【问题标题】:Read from Excel interop and write distinct values to another sheet从 Excel 互操作读取并将不同的值写入另一个工作表
【发布时间】:2012-02-16 09:08:47
【问题描述】:

我正在使用 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

那么不同的工作表应该有(每列中的排序并不重要):

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

任何人都可以提出一种更简单的方法(仍然使用 com interop excel),不需要使用这种丑陋的 2d 对象数组、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();
}

【问题讨论】:

    标签: c# .net excel c#-4.0 com


    【解决方案1】:

    我认为您可以按列执行此操作,并使用 linq 选择不同的值,然后将它们写入目标。 像这样:

    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);
    

    【讨论】:

    • 我应该在方法体中放什么?它还说这个错误:'无法解析符号 T' 谢谢
    • 对不起,我更正了错误的语法。你应该使用 excel API 在第一个中读取数据,在第二个中你必须将它们写入工作表中。
    • 也许我在这里遗漏了一些东西......但是那个空的方法体如何让你阅读任何东西?
    • 其实你应该实现body :)
    猜你喜欢
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    相关资源
    最近更新 更多