64 lines
No EOL
2.2 KiB
C#
64 lines
No EOL
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using OfficeOpenXml;
|
|
|
|
namespace JD.MapFileFontReader.Service
|
|
{
|
|
public class EPPlusCsvDataReader : ICsvDataReader
|
|
{
|
|
/// <summary>
|
|
/// Returns the data of the specified worksheet as a CsvData structure.
|
|
/// </summary>
|
|
public CsvData FromExcelFile(string filePath, string worksheetName)
|
|
{
|
|
if (!File.Exists(filePath)) throw new FileNotFoundException(filePath);
|
|
|
|
var result = new CsvData();
|
|
|
|
using (var package = new ExcelPackage(new FileInfo(filePath)))
|
|
{
|
|
//Get the Worksheet containing the data
|
|
var ws = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == worksheetName);
|
|
|
|
// No worksheet -> ERROR
|
|
if (ws == null)
|
|
{
|
|
throw new Exception(
|
|
$"Cannot find worksheet {worksheetName} in excel {Path.GetFileName(filePath)}, " +
|
|
$"found only '{string.Join(", ", package.Workbook.Worksheets)}'");
|
|
}
|
|
|
|
if (ws.Dimension == null) return result;
|
|
|
|
// Add the column names as they are in the first row
|
|
for (int j = ws.Dimension.Start.Column; j < ws.Dimension.Columns; j++)
|
|
{
|
|
result.ColumnNames.Add(ws.Cells[ws.Dimension.Start.Row, j].Text.Replace(" ", "_"));
|
|
}
|
|
|
|
// Get all cells grouped row by row (excluding the first row)
|
|
for (int i = ws.Dimension.Start.Row + 1; i < ws.Dimension.Rows; i++)
|
|
{
|
|
List<string> line = new List<string>();
|
|
|
|
for (int j = ws.Dimension.Start.Column; j < ws.Dimension.Columns; j++)
|
|
{
|
|
using (var row = ws.Cells[i, j])
|
|
{
|
|
line.Add(row.Text);
|
|
}
|
|
}
|
|
|
|
// Add the line as data rows
|
|
result.Rows.Add(new CsvData.Row(result.ColumnNames, line));
|
|
}
|
|
|
|
ws.Dispose();
|
|
|
|
return result;
|
|
}
|
|
}
|
|
}
|
|
} |