.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
Листинг программы
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using DocumentFormat.OpenXml.Packaging;
  5. using DocumentFormat.OpenXml.Spreadsheet;
  6.  
  7. namespace OpenExcelTest
  8. {
  9.     internal class Program
  10.     {
  11.         private static void Main()
  12.         {
  13.             const string source = "file.xlsx";
  14.             const string filename = "result.xlsx";
  15.             File.Copy(source, filename, true);
  16.             using (SpreadsheetDocument doc = SpreadsheetDocument.Open(filename, true))
  17.             {
  18.                 WorkbookPart workbookPart = doc.WorkbookPart;
  19.  
  20.                 WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
  21.                 Worksheet sheet = worksheetPart.Worksheet;
  22.  
  23.                 var cells = sheet.Descendants<Cell>().ToList();
  24.                 var rows = sheet.Descendants<Row>().ToList();
  25.  
  26.                 Console.WriteLine(cells.LongCount());
  27.                 Console.WriteLine(rows.LongCount());
  28.  
  29.                 foreach (Cell cell in cells)
  30.                 {
  31.                     if (cell.CellValue != null)
  32.                     {
  33.                         Console.WriteLine("Cell contents: {0}", cell.CellValue.Text);
  34.                     }
  35.                 }
  36.  
  37.                 Cell newCell = InsertCellInWorksheet("A", 5, worksheetPart);
  38.                 newCell.CellValue = new CellValue("100500");
  39.  
  40.                 sheet.Save();
  41.             }
  42.         }
  43.  
  44.         private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
  45.         {
  46.             Worksheet worksheet = worksheetPart.Worksheet;
  47.             var sheetData = worksheet.GetFirstChild<SheetData>();
  48.             string cellReference = columnName + rowIndex;
  49.  
  50.             // If the worksheet does not contain a row with the specified row index, insert one.
  51.             Row row;
  52.             if (sheetData.Elements<Row>().Count(r => r.RowIndex == rowIndex) != 0)
  53.             {
  54.                 row = sheetData.Elements<Row>().First(r => r.RowIndex == rowIndex);
  55.             }
  56.             else
  57.             {
  58.                 row = new Row {RowIndex = rowIndex};
  59.                 sheetData.Append(row);
  60.             }
  61.  
  62.             // If there is not a cell with the specified column name, insert one.  
  63.             if (row.Elements<Cell>().Any(c => c.CellReference.Value == columnName + rowIndex))
  64.             {
  65.                 return row.Elements<Cell>().First(c => c.CellReference.Value == cellReference);
  66.             }
  67.             // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
  68.             Cell refCell =
  69.                 row.Elements<Cell>()
  70.                    .FirstOrDefault(
  71.                                    cell =>
  72.                                    String.Compare(cell.CellReference.Value, cellReference,
  73.                                                   StringComparison.OrdinalIgnoreCase) > 0);
  74.  
  75.             var newCell = new Cell {CellReference = cellReference};
  76.             row.InsertBefore(newCell, refCell);
  77.  
  78.             worksheet.Save();
  79.             return newCell;
  80.         }
  81.     }
  82. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 3.8 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы