.NET 3.x Работа с документами Excel без Microsoft.Office.Interop.Excel - C#
Формулировка задачи:
всем добрый день
все дело в том что для своих программ я использую БД Excel
но! однако не все устанавливают на компьютере Office, да и не правильно от пользователей требовать что бы они устанавливали его.... . в общем отсюда же проблема с Microsoft.Office.Interop.Excel
мне нужно с проекта убрать(заменить) Microsoft.Office.Interop так что бы все не зависимо от того что у них установлен office или нет могли пользоваться программой!
может кто-то знает как можно обойтись без Microsoft.Office.Interop.. и спокойно работать с excel?
буду очень признателен!
Решение задачи: «.NET 3.x Работа с документами Excel без Microsoft.Office.Interop.Excel»
textual
Листинг программы
- using System;
- using System.IO;
- using System.Linq;
- using DocumentFormat.OpenXml.Packaging;
- using DocumentFormat.OpenXml.Spreadsheet;
- namespace OpenExcelTest
- {
- internal class Program
- {
- private static void Main()
- {
- const string source = "file.xlsx";
- const string filename = "result.xlsx";
- File.Copy(source, filename, true);
- using (SpreadsheetDocument doc = SpreadsheetDocument.Open(filename, true))
- {
- WorkbookPart workbookPart = doc.WorkbookPart;
- WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
- Worksheet sheet = worksheetPart.Worksheet;
- var cells = sheet.Descendants<Cell>().ToList();
- var rows = sheet.Descendants<Row>().ToList();
- Console.WriteLine(cells.LongCount());
- Console.WriteLine(rows.LongCount());
- foreach (Cell cell in cells)
- {
- if (cell.CellValue != null)
- {
- Console.WriteLine("Cell contents: {0}", cell.CellValue.Text);
- }
- }
- Cell newCell = InsertCellInWorksheet("A", 5, worksheetPart);
- newCell.CellValue = new CellValue("100500");
- sheet.Save();
- }
- }
- private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
- {
- Worksheet worksheet = worksheetPart.Worksheet;
- var sheetData = worksheet.GetFirstChild<SheetData>();
- string cellReference = columnName + rowIndex;
- // If the worksheet does not contain a row with the specified row index, insert one.
- Row row;
- if (sheetData.Elements<Row>().Count(r => r.RowIndex == rowIndex) != 0)
- {
- row = sheetData.Elements<Row>().First(r => r.RowIndex == rowIndex);
- }
- else
- {
- row = new Row {RowIndex = rowIndex};
- sheetData.Append(row);
- }
- // If there is not a cell with the specified column name, insert one.
- if (row.Elements<Cell>().Any(c => c.CellReference.Value == columnName + rowIndex))
- {
- return row.Elements<Cell>().First(c => c.CellReference.Value == cellReference);
- }
- // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
- Cell refCell =
- row.Elements<Cell>()
- .FirstOrDefault(
- cell =>
- String.Compare(cell.CellReference.Value, cellReference,
- StringComparison.OrdinalIgnoreCase) > 0);
- var newCell = new Cell {CellReference = cellReference};
- row.InsertBefore(newCell, refCell);
- worksheet.Save();
- return newCell;
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д