Excel工作表重命名将无法工作

我想重命名指定的工作表,并把一些处理的数据,但下面的代码(这看起来几乎相同,我可以find这个和其他网站上的每个例子)只是不会我想要的:

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

这个exception永远不会抛出,所以代码不包含任何错误,但是我打开的文档中的工作表仍然具有相同的名称。 另外,

 Debug.WriteLine(...) 

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

编辑:

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

当你完成后你有没有试过closuresExcel?

我不能完全弄清楚你从哪里gettng 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); 

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