Excel工作表重命名不起作用

时间:2014-08-06 11:01:08

标签: c# excel renaming

我想重命名指定的工作表并在其上放置一些处理过的数据,但是下面的代码(看起来和我在这个和其他网站上找到的每个例子几乎相同)只是赢得了我想要的东西:

try
{
    xl.Worksheet = (ExcelRefer.Worksheet) xl.Workbook.Worksheets.get_Item("Sheet1");
    xl.Worksheet.Name = "Smoothed result";
    xl.Workbook.Save();
    xl.Range = xl.Worksheet.UsedRange;

    Debug.WriteLine("Saved");
}
catch(Exception exception)
{
    MessageBox.Show(exception.Message);
}

永远不会抛出异常,因此代码不包含任何错误,但我打开的文档中的工作表仍然具有相同的名称。

Debug.WriteLine(...)
调用

方法并正确显示输出。当我告诉工作簿保存时,它甚至会问我是否要覆盖现有文件。谁能告诉我我做错了什么?

修改:

xl是一个类的对象,包含使用excel的所有必要元素。

using ExcelRefer = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;

using ZedGraph;
class XLSXMulti
{
    private static List<int[]> dataPositions = new List<int[]>();
    private static PointPairList measureData = new PointPairList();
    private static PointPairList[] dataComparison = new PointPairList[2];
    private static bool smoothing = false;
    private static bool measureDataFound = false;
    private static bool fileFinished = false;
    private static string[] excelFilePaths;
    private static string[] temp;
    private static int numberOfSamples;
    private static BackgroundWorker[] bwg;
    private static ProgressBar pbExcel;

    public static void Init(string[] filePaths, ProgressBar pb, bool smooth)
    {
        excelFilePaths = filePaths;
        pbExcel = pb;
        smoothing = smooth;
        measureData.Clear();
        dataPositions.Clear();

        temp = Interaction.InputBox("Number of consecutive values to be used " +
                                    "for smoothing and the iteration step. These values" +
                                    " will be used for all selected files.\n" +
                                    "IMPORTANT: The two values have to be separated with a ','!",
                                    "Select grade of smoothing",
                                    "5,1", 500, 480).Split(',');


        bwg = new BackgroundWorker[Environment.ProcessorCount];
        for(int i = 0; i < bwg.Length; i ++)
        {
            bwg[i] = new BackgroundWorker();
        }

        foreach(BackgroundWorker bw in bwg)
        {
            bw.DoWork += bwg_doWork;
            bw.ProgressChanged += bwg_ProgressChanged;
            bw.RunWorkerCompleted += bwg_RunworkerCompleted;

            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;
        }

        List<string>[] filesForWorkers = new List<string>[bwg.Length];
        for(int i = 0; i < filesForWorkers.Length; i ++)
        {
            filesForWorkers[i] = new List<string>();
        }

        int filesPerWorker = filePaths.Length / bwg.Length;
        int workerindex = 0;

        MessageBox.Show("filesPerWorker: " + filesPerWorker + "\n" +
                        "filePaths: " + filePaths.Length + "\n" +
                        "bwg: " + bwg.Length);

        for(int i = 0; i < filePaths.Length; i ++)
        {
            filesForWorkers[workerindex].Add(filePaths[i]);

            workerindex ++;
            if(workerindex == bwg.Length)
            {
                workerindex = 0;
            }
        }

        for(int i = 0; i < bwg.Length; i ++)
        {
            bwg[i].RunWorkerAsync(filesForWorkers[i]);
        }
    }

    private static void bwg_doWork(object sender, DoWorkEventArgs e)
    {
        List<string> filelist = e.Argument as List<string>;
        Excelattributes xl = new Excelattributes();

        foreach(string s in filelist)
        {
            try
            {
                xl.App = new ExcelRefer.Application();
                xl.Workbook = xl.App.Workbooks.Open(s, 0, true, 5, "", "", true, 
                                                        Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xl.Worksheet = (ExcelRefer.Worksheet)xl.Workbook.Worksheets.get_Item(1); // Zugriff auf eingegebenes Tabellenblatt
                xl.Range = xl.Worksheet.UsedRange;

                findMeasureData(xl);

                if(xl.Workbook != null){xl.Workbook.Close(true, null, null);}
                if(xl.App != null) {xl.App.Quit();}
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "Exception");
            }
            finally
            {
                if(xl.Workbook != null){xl.Workbook.Close(true, null, null);}
                if(xl.App != null) {xl.App.Quit();}
            }
        }
    }

    private static void bwg_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // TODO: implement some sort of progress reporting
    }

    private static void bwg_RunworkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Statuslabel.label.Text = "Backgroundworker finished";
        (sender as BackgroundWorker).Dispose();
    }

    private static void findMeasureData(Excelattributes xl)
    {
        // Erste 15 Zeilen durchgehen, um herauszufinden wo die Messwerte beginnen (9 + 6 Sicherheit)
        // Nur bis inkl. Spalte AZ
        try
        {
            for(int zeile = 1; zeile <= 15; zeile ++)
            {
                for(int spalte = 1; spalte <= 52; spalte ++)
                {
                    // WICHTIG: (xl.Range...).Text verwenden, um Nullreferenceexception zu vermeiden [?]
                    Object zelleninhalt = (xl.Range.Cells[zeile, spalte] as ExcelRefer.Range).Text;

                    if(zelleninhalt.Equals("DATA START"))
                    {
                        dataPositions.Add(new int[2] {zeile +1, spalte +1});
                        measureDataFound = true;
                    }
                    else if(zelleninhalt.Equals("Number of Samples"))
                    {
                        numberOfSamples = Convert.ToInt32((xl.Range.Cells[zeile, spalte+1] as
                                                           ExcelRefer.Range).Text);
                    }
                }
            }

            if(measureDataFound == true)
            {
                int[,] temp = new int[dataPositions.Count, 2];
                for(int i = 0; i < dataPositions.Count; i ++)
                {
                    temp[i, 0] = dataPositions.ElementAt(i).ToArray()[0];
                    temp[i, 1] = dataPositions.ElementAt(i).ToArray()[1];
                }
                readMeasureData(temp, xl);
            }
        }
        catch(Exception exception)
        {
            MessageBox.Show(exception.Message, "Exception");
        }
    }

    private static void readMeasureData(int[,] temp, Excelattributes xl)
    {
        int[,] zellen = temp;
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for(int i = zellen[0,0]; i < (zellen[0,0] + numberOfSamples); i ++)
        {
            try
            {
                double weg = Convert.ToDouble((xl.Range.Cells[i, zellen[0,1]] as ExcelRefer.Range).Value2);
                double kraft = Convert.ToDouble((xl.Range.Cells[i, zellen[1,1]] as ExcelRefer.Range).Value2);

                measureData.Add(new PointPair(weg, kraft));

            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "Exception");
                Application.Exit();
            }
        }
        stopwatch.Stop();
        MessageBox.Show(stopwatch.ElapsedMilliseconds / 1000 + " Sekunden");

        dataComparison[0] = measureData;
        if(smoothing == true)
        {
            smoothMeasureData(xl);
        }
    }

    private static void smoothMeasureData(Excelattributes xl)
    {
        if(temp != null)
        {
            try
            {
                int[] smoothParameters = new int[]{Convert.ToInt32(temp[0]), Convert.ToInt32(temp[1])};
                if(smoothParameters[1] == 0) {smoothParameters[1] = 1;}

                PointPairList smoothedData = new PointPairList();

                MessageBox.Show("Glätte...\n" + smoothParameters[0] + " " + measureData.Count);

                for(int i = (smoothParameters[0] -1); i < measureData.Count; i += smoothParameters[1])
                {
                    double durchschnittX = 0;
                    double durchschnittY = 0;

                    for(int x = i; x > (i - (smoothParameters[0])); x --)
                    {
                        durchschnittX += measureData.ElementAt(x).X;
                        durchschnittY += measureData.ElementAt(x).Y;
                    }

                    durchschnittX /= (double) smoothParameters[0];
                    durchschnittY /= (double) smoothParameters[0];

                    smoothedData.Add(new PointPair(durchschnittX, durchschnittY));
                }

                dataComparison[0] = measureData;
                dataComparison[1] = smoothedData;

                writeToXLSX(smoothedData, xl);
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "Exception");
            }
        }
    }

    private static void writeToXLSX(PointPairList smoothedData, Excelattributes xl)
    {
        try
        {
            xl.Worksheet = (ExcelRefer.Worksheet) xl.Workbook.Worksheets.get_Item("Sheet1");
            xl.Worksheet.Name = "Smoothed result";
            xl.Workbook.Save();
            xl.Workbook.Close(true, null, null);
            xl.Range = xl.Worksheet.UsedRange;

            Debug.WriteLine("Saved");
        }
        catch(Exception exception)
        {
            MessageBox.Show(exception.Message);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

你完成后是否尝试过关闭Excel?

我无法确定您从哪里获取xl,但以下代码适用于我:

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook book = xlApp.Workbooks.Open(@"C:\test.xlsx");
Worksheet xl = book.Worksheets.get_Item("sheet1");
xl.Name = "Smoothed result";
book.Save();
book.Close();

修改

看到用于打开工作簿的代码后,我认为存在问题。您正在使用以下方式打开文件:

xl.Workbook = xl.App.Workbooks.Open(s, 0, true, 5, "", "", true, 
               Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

第三个参数是ReadOnly参数,您已将其设置为true。尝试将其设置为false