Excel Interop - insert&按行添加数据

时间:2015-05-28 00:43:06

标签: c# excel

嘿伙计我需要在excel中的某一行下面插入空行,然后将数据添加到我插入的那些空行中...

到目前为止,我能够创建空行但是我有一段时间试图找出如何将Range.Value设置为String类型的数组

插入行的方法:

private void shiftRows(int from, int numberof)
    {
        from++;
        Range r = oXL.get_Range("A" + from.ToString(), "A" + from.ToString()).EntireRow;

        for (int i = 0; i < numberof; i++)
            r.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown);
    }
 // so this would shift the below rows by numberof times. 

这个方法目前是我所坚持的...这是一次一行地将数组插入新行

    public void inputRowData(string[] data, int rds)
    {
        int bestRow = getRowByRDS(rds);
        string val = getValueOfCell(bestRow, 6);
        if (val == null || val.Equals(""))
        {
            shiftRows(bestRow, data.Length);
            string[] formatedData = formatOutput(bestRow, data);
            for (int i = 0; i < formatedData.Length; i++)
            {
                Range r = oSheet.get_Range((bestRow + i).ToString() + ":" + (bestRow + i).ToString());
                r.set_Value(formatedData[i].Split('\t'));

// have tried r.Value = formatedData[i].Split('\t')
// formatedData is an array of string which contains data for each cell seperated by a tab

            }

        }
        else
        {
            Console.WriteLine("Line has some information already, skipping 1 more");
            shiftRows(bestRow, data.Length + 1);
        }

    }

1 个答案:

答案 0 :(得分:1)

我强烈建议你:

  • NOT 插入行但只写空行(安全和性能)
  • 设置一个大型数组对象,只在 ONE 中写入excel(性能)

例子(我保留了shiftrows,但你应该真的摆脱它):

public void inputRowData(string[] data, int rds)
{
    int bestRow = getRowByRDS(rds);
    string val = getValueOfCell(bestRow, 6);
    if (val == null || val.Equals(""))
    {
        shiftRows(bestRow, data.Length);
        string[] formatedData = formatOutput(bestRow, data);
        // transform formated data into string[,]
        var string[][] splitedData = formatedData.Select(s => s.Split('\t')).ToArray();
        var colCount = splitedData.Max(r => r.Lenght);
        var excelData = new string[splitedData.Length, colCount]
        for (int i = 0; i < splitedData.Length; i++)
        {
            for (int j = 0; j < splitedData[i].Length; j++)
            {
                 excelData[i,j] = splitedData[i][j];
            }
        }
        oSheet.get_Range("A" + bestRow.ToString()).Resize(splitedData.Length, colCount).Value = excelData;
    }
    else
    {
        Console.WriteLine("Line has some information already, skipping 1 more");
        shiftRows(bestRow, data.Length + 1);
    }

}