ExcelConverter.ExcelReader.Read C# (CSharp) Method

Read() public method

public Read ( ) : ExcelTable
return ExcelTable
        public ExcelTable Read()
        {
            var application = new Application();
            var workbook = application.Workbooks.Open(_path);
            var worksheet = workbook.Worksheets[1] as Worksheet;
            var range = worksheet.UsedRange;
            var valueArray = (object[,])range.get_Value(XlRangeValueDataType.xlRangeValueDefault);
            var table = new ExcelTable();

            for (int header = 1; header <= valueArray.GetLength(1); header++)
            {
                table.Headers.Add(valueArray[1, header].ToString());
            }

            for (int row = 2; row <= valueArray.GetLength(0); row++)
            {
                var dataRow = new List<string>();
                for (int col = 1; col <= valueArray.GetLength(1); col++)
                {
                    var value = valueArray[row, col];
                    dataRow.Add(value == null ? null : value.ToString());
                }
                table.Data.Add(dataRow);
            }

            workbook.Close();
            Marshal.ReleaseComObject(workbook);
            return table;
        }

Usage Example

Esempio n. 1
0
 static void Main(string[] args)
 {
     var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
     var workbookPath = Path.Combine(dir, "PLIB APIs.xlsx");
     var excelReader = new ExcelReader(workbookPath);
     var excelTable = excelReader.Read();
     var collection = (new ExcelAdapter()).Convert(excelTable);
     Console.WriteLine("Converting Excel to text file...");
     var writer = new TextWriter(Path.Combine(dir, "PLIB APIs.txt"));
     writer.Write(collection);
     Console.WriteLine("Conversion completed.");
 }