Я использую Open XML SDK, чтобы открыть файл Excel и получить значения ячеек из всех строк и столбцов, содержащих данные на листе. Вот мой код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ReadingExcel
{
class RetrieveListOfExcelValues
{
static void Main(string[] args)
{
String fileName = @"C:\Users\Documents\TestReadingExcel.xlsx";
// Comment one of the following lines to test the method separately.
ReadExcelFileDOM(fileName); // DOM
} //end Main
static void ReadExcelFileDOM(string fileName)
{
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
// Retrieve a reference to the workbook part.
WorkbookPart wbPart = document.WorkbookPart;
//Worksheet name that is the the workbook
string sheetName = "Sheet1";
// Find the sheet with the supplied name, and then use that
// Sheet object to retrieve a reference to the first worksheet.
Sheet theSheet = wbPart.Workbook.Descendants().
Where(s => s.Name == sheetName).FirstOrDefault();
// Throw an exception if there is no sheet.
if (theSheet == null)
{
throw new ArgumentException("sheetName");
}
// Retrieve a reference to the worksheet part.
WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
string parseCellValue;
foreach (Row r in theSheet.Elements())
{
foreach (Cell c in r.Elements())
{
Cell theCell = wsPart.Worksheet.Descendants().FirstOrDefault();
parseCellValue = GetCellValue(theCell, wbPart);
Console.Write(parseCellValue + " ");
//text = c.CellValue.Text;
//Console.Write(text + " ");
}
}
Console.WriteLine();
Console.ReadKey();
}
} //end ReadExcelFileDOMMethod
public static string GetCellValue(Cell cell, WorkbookPart wbPart)
{
string value = null;
if (cell != null)
{
value = cell.InnerText;
// If the cell represents an integer number, you are done.
// For dates, this code returns the serialized value that
// represents the date. The code handles strings and
// Booleans individually. For shared strings, the code
// looks up the corresponding value in the shared string
// table. For Booleans, the code converts the value into
// the words TRUE or FALSE.
if (cell.DataType != null)
{
switch (cell.DataType.Value)
{
case CellValues.SharedString:
// For shared strings, look up the value in the
// shared strings table.
var stringTable = wbPart.GetPartsOfType()
.FirstOrDefault();
// If the shared string table is missing, something
// is wrong. Return the index that is in
// the cell. Otherwise, look up the correct text in
// the table.
if (stringTable != null)
{
value = stringTable.SharedStringTable.ElementAt(
int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value =
"FALSE";
break;
default:
value =
"TRUE";
break;
}
break;
}
}
}
return value;
}
}
}
Текст не отображается на консоли, и я не могу точно понять, что я делаю не так в этом коде. Это моя первая попытка использования Open XML. Возможно, я что-то упустил из виду или нужно переместить несколько строк кода.
Как мне получить все значения ячеек из строк и столбцов на листе для отображения на консоли?
Формат Excel
A1 B1 C1
Fruit Lot Date
Banana 4 4/13/2014
Orange 6 5/01/2014
Apple 9 3/14/2014
Подробнее здесь: https://stackoverflow.com/questions/237 ... ml-sdk-2-0
Получите все значения ячеек в каждой строке и столбце с помощью Open XML SDK 2.0. ⇐ C#
Место общения программистов C#
1770267710
Anonymous
Я использую Open XML SDK, чтобы открыть файл Excel и получить значения ячеек из всех строк и столбцов, содержащих данные на листе. Вот мой код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ReadingExcel
{
class RetrieveListOfExcelValues
{
static void Main(string[] args)
{
String fileName = @"C:\Users\Documents\TestReadingExcel.xlsx";
// Comment one of the following lines to test the method separately.
ReadExcelFileDOM(fileName); // DOM
} //end Main
static void ReadExcelFileDOM(string fileName)
{
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
// Retrieve a reference to the workbook part.
WorkbookPart wbPart = document.WorkbookPart;
//Worksheet name that is the the workbook
string sheetName = "Sheet1";
// Find the sheet with the supplied name, and then use that
// Sheet object to retrieve a reference to the first worksheet.
Sheet theSheet = wbPart.Workbook.Descendants().
Where(s => s.Name == sheetName).FirstOrDefault();
// Throw an exception if there is no sheet.
if (theSheet == null)
{
throw new ArgumentException("sheetName");
}
// Retrieve a reference to the worksheet part.
WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
string parseCellValue;
foreach (Row r in theSheet.Elements())
{
foreach (Cell c in r.Elements())
{
Cell theCell = wsPart.Worksheet.Descendants().FirstOrDefault();
parseCellValue = GetCellValue(theCell, wbPart);
Console.Write(parseCellValue + " ");
//text = c.CellValue.Text;
//Console.Write(text + " ");
}
}
Console.WriteLine();
Console.ReadKey();
}
} //end ReadExcelFileDOMMethod
public static string GetCellValue(Cell cell, WorkbookPart wbPart)
{
string value = null;
if (cell != null)
{
value = cell.InnerText;
// If the cell represents an integer number, you are done.
// For dates, this code returns the serialized value that
// represents the date. The code handles strings and
// Booleans individually. For shared strings, the code
// looks up the corresponding value in the shared string
// table. For Booleans, the code converts the value into
// the words TRUE or FALSE.
if (cell.DataType != null)
{
switch (cell.DataType.Value)
{
case CellValues.SharedString:
// For shared strings, look up the value in the
// shared strings table.
var stringTable = wbPart.GetPartsOfType()
.FirstOrDefault();
// If the shared string table is missing, something
// is wrong. Return the index that is in
// the cell. Otherwise, look up the correct text in
// the table.
if (stringTable != null)
{
value = stringTable.SharedStringTable.ElementAt(
int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value =
"FALSE";
break;
default:
value =
"TRUE";
break;
}
break;
}
}
}
return value;
}
}
}
Текст не отображается на консоли, и я не могу точно понять, что я делаю не так в этом коде. Это моя первая попытка использования Open XML. Возможно, я что-то упустил из виду или нужно переместить несколько строк кода.
Как мне получить все значения ячеек из строк и столбцов на листе для отображения на консоли?
Формат Excel
A1 B1 C1
Fruit Lot Date
Banana 4 4/13/2014
Orange 6 5/01/2014
Apple 9 3/14/2014
Подробнее здесь: [url]https://stackoverflow.com/questions/23769010/retrieve-all-cell-values-in-each-row-and-column-with-open-xml-sdk-2-0[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия