[OpenXml] Read/Write row/cell from excel
2015-07-27 13:34
543 查看
public static void test(){ using (SpreadsheetDocument document = SpreadsheetDocument.Open("test.xlsx", true)) { WorkbookPart workbookPart = document.WorkbookPart; string relId = workbookPart.Workbook.Descendants<Sheet>().First(sheet => sheet.Name.Value.ToLower().Equals("sheet1")).Id; WorksheetPart worksheetpart = (WorksheetPart)workbookPart.GetPartById(relId); DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = worksheetpart.Worksheet; SheetData sheetData = worksheet.GetFirstChild<SheetData>(); for (int i = 2; i <= 3; i++) { Row row = new Row() { RowIndex = (uint)i }; row.Append(new Cell() { CellReference = "A" + i, DataType = CellValues.String, CellValue = new CellValue("kaka") });//, StyleIndex = styleIndex }); row.Append(new Cell() { CellReference = "B" + i, DataType = CellValues.String, CellValue = new CellValue("2") });//, StyleIndex = styleIndex }); row.Append(new Cell() { CellReference = "C" + i, DataType = CellValues.String, CellValue = new CellValue("GENERAL MANAGEMENT") });//, StyleIndex = styleIndex }); row.Append(new Cell() { CellReference = "D" + i, DataType = CellValues.String, CellValue = new CellValue("2") });//, StyleIndex = styleIndex }); row.Append(new Cell() { CellReference = "E" + i, DataType = CellValues.String, CellValue = new CellValue((1 == 1).ToString()) });//, StyleIndex = styleIndex }); sheetData.Append(row); } // loop each row to get value; string cellValue = GetCellValue(sheetData.Descendants<Row>().ElementAt<Row>(0), "A", getSharedString(document)); worksheet.Save(); } } private static List<SharedStringItem> getSharedString(SpreadsheetDocument document) { WorkbookPart workbookPart = document.WorkbookPart; return workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ToList<SharedStringItem>(); } // cell could be null private static Cell GetCell(Row row, string columnName) { return row.Descendants<Cell>().FirstOrDefault(p => p.CellReference == columnName + row.RowIndex); } // call getSharedString // call GetCell // => retrieve cell value public static string GetCellValue(Row row, string columnName, List<SharedStringItem> sharedStrings) { Cell cell = GetCell(row, columnName); if (cell == null) { return null; } string value = ""; if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString) { SharedStringItem item = sharedStrings.ElementAt<SharedStringItem>(Int32.Parse(cell.CellValue.Text)); value = item.InnerText; } else { value = cell.CellValue.Text; } return value; }
相关文章推荐
- linux初学(十)之linux文件系统挂载管理
- linux下安装node.js
- Nginx中发送udp请求
- linux修改文件权限
- linux初学(九)之linux文件系统
- linux初学(八)之使用fdisk进行磁盘管理
- mac shell终端编辑命令行快捷键——行首行尾
- Linux文件的软链接和硬链接
- Linux文件的软链接和硬链接
- linux初学(七)之磁盘基本概念
- linux初学(六)之linux系统基础
- 网站项目系列 第一篇
- [OpenXml] Generate excel in memory and dump to file
- Tomcat 简介
- 14、Linux例行性工作排程
- 每天一个Linux命令-11(SFTP命令)
- Linux 编程学习笔记----命令行参数处理
- 谈网站域名,备案到上线
- shell 入门教程
- dubbo总结(6)——linux对dubbo的维护