Home > Mobile >  Rename an Excel Workbook
Rename an Excel Workbook

Time:12-09

I am trying to rename my Excel Workbook. Currently I am just saving the file name from my program, but I do not want a message that asks if I want to overwrite the file that already exists, which is my current issue. Having a temporary file name may not be the way to go about doing this so if there are better recommendations please inform me.

Without the excelWorkbook.SaveAs("Test Name"); line, the file gives a random tmp name.

 private void excelfunc()
        {
            string tempPath = System.IO.Path.GetTempFileName();

            System.IO.File.WriteAllBytes(tempPath, Properties.Resources.excelResource);

            Excel.Application excelApplication = new Excel.Application();
            Excel._Workbook excelWorkbook;
            excelWorkbook = excelApplication.Workbooks.Open(tempPath);
            excelWorkbook.SaveAs("Test Name");
            excelApplication.Visible = true; // at this point its up to the user to save the file

        }

UPDATE: I added in a line that overwrites the existing file, but I am now getting an error message that says: "System.IO.IOException: 'Cannot create a file when that file already exists."

 private void excelfunc()
        {
            string tempPath = System.IO.Path.GetTempFileName();
            MessageBox.Show(tempPath);
            System.IO.File.WriteAllBytes(tempPath, Properties.Resources.excelResource);

            Excel.Application excelApplication = new Excel.Application();
            Excel._Workbook excelWorkbook;
            File.Move(tempPath, "Test Name");
            excelWorkbook = excelApplication.Workbooks.Open(tempPath);         
            excelApplication.Visible = true; // at this point its up to the user to save the file
}

CodePudding user response:

System.IO.File.Move("oldfilename", "newfilename");

  • Related