Rename the Excel Sheet Name in C#
VS 2008 / C#.
On passing the File path of a Spreadsheet, i need to rename the Sheet.
How to rename the Sheet1 of the Excel Sheet as 开发者_StackOverflow社区"ABC".
We exporting an Excel Sheet to the SQL Database. Records in the Excel Sheet are manually edited and updated by end user. Column Values can have different datatypes.
By default, a Spread Sheet will have three Sheets as Sheet1, Sheet2,Sheet3.
End Users, usually work on Sheet1. We need to maintain a static name for this Sheet1 which helps us to Export the Sheet1 to SQL Database.
If we renamed the Sheet1 as ABC, we are maintaining the same Name. We cant export default sheet as like that. Because, End users may change their name or stick with default name on it.
In order to avoid confusion, we decided to rename the Sheet1 of the Spread Sheet.
C# 3.0
using Microsoft.Office.Interop.Excel;
Then
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass xl = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook xlBook;
Microsoft.Office.Interop.Excel.Worksheet xlSheet;
string laPath = System.IO.Path.GetFullPath("C:\\ExcelSheet.xls");
xlBook = (Workbook)xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
xlSheet = (Worksheet)xlBook.Worksheets.get_Item(1);
xlSheet.Name = "CIAO";
xlBook.Save();
xl.Application.Workbooks.Close();
C# 4.0+
The difference is: no more System.Reflection.Missing.Value
and using DLR (Dynamic Language Runtime)
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
Then
var excelFile = Path.GetFullPath("C:\\ExcelSheet.xls");
var excel = new Excel.Application();
var workbook = excel.Workbooks.Open(excelFile);
var sheet = (Excel.Worksheet)workbook.Worksheets.Item[1]; // 1 is the first item, this is NOT a zero-based collection
sheet.Name = DateTime.Now.ToString("yyyyMMddHHmmss");
workbook.Save();
excel.Application.Workbooks.Close();
精彩评论