博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Open Xml 创建Excel并插入数据
阅读量:5075 次
发布时间:2019-06-12

本文共 3788 字,大约阅读时间需要 12 分钟。

创建Excel

private static void CreateSpreadSheet()        {            string fileName = "E:\\01.xlsx";            string sheetName = "test";            using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook))            {                // create the workbook                  spreadSheet.AddWorkbookPart();                spreadSheet.WorkbookPart.Workbook = new Workbook();     // create the worksheet                  spreadSheet.WorkbookPart.AddNewPart
(); spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet(); SharedStringTablePart m_SharedStringTablePart = spreadSheet.WorkbookPart.AddNewPart
(); // create sheet data SheetData m_SheetData = new SheetData(); spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.AppendChild(m_SheetData); // create row //spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.First().AppendChild(new Row()); //// create cell with data //spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.First().First().AppendChild(new Cell() { CellValue = new CellValue("100") }); //Add Data Row row1 = new Row() { RowIndex = 1 }; Cell cell1 = new Cell() { CellReference = "A1" }; int index = InsertSharedStringItem("Sun", m_SharedStringTablePart); cell1.CellValue = new CellValue(index.ToString()); cell1.DataType = new EnumValue
(CellValues.SharedString); row1.Append(cell1); m_SheetData.Append(row1); // save worksheet spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.Save(); // create the worksheet to workbook relation spreadSheet.WorkbookPart.Workbook.AppendChild(new Sheets()); spreadSheet.WorkbookPart.Workbook.GetFirstChild
().AppendChild(new Sheet() { Id = spreadSheet.WorkbookPart.GetIdOfPart(spreadSheet.WorkbookPart.WorksheetParts.First()), SheetId = 1, Name = sheetName }); spreadSheet.WorkbookPart.Workbook.Save(); } } private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart) { // If the part does not contain a SharedStringTable, create one. if (shareStringPart.SharedStringTable == null) { shareStringPart.SharedStringTable = new SharedStringTable(); shareStringPart.SharedStringTable.Count = 1; shareStringPart.SharedStringTable.UniqueCount = 1; } int i = 0; // Iterate through all the items in the SharedStringTable. If the text already exists, return its index. foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements
()) { if (item.InnerText == text) { return i; } i++; } // The text does not exist in the part. Create the SharedStringItem and return its index. shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text))); shareStringPart.SharedStringTable.Save(); return i; }

 

posted on
2012-08-28 13:53  阅读(
...) 评论(
...) 收藏

转载于:https://www.cnblogs.com/sshoub/archive/2012/08/28/2660152.html

你可能感兴趣的文章