Другие языки программирования и технологии

Как заполнить массив данными из Экселя в с#

Как заполнить массив данными из Экселя в с#
***вова*** ***кан***
***вова*** ***кан***
86 925
Лучший ответ
Могу подарить соотв. класс, адаптируй под свои нужды:

public class ExcelInfo
{
public int MaxX { get; set; }
public int MaxY { get; set; }
public int DataStart { get; set; }
}

public static class ExcelAccess
{
private static Application Excel = null;
private static Workbook Book = null;
private static Worksheet Sheet = null;

public static string IntToExcelCoord(int _a)
{
const string AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string Result = "";
do
{
_a--;
if (_a < 0)
_a = 0;
Result = AB[_a % 26].ToString() + Result;
_a /= 26;
}
while (_a > 0);
return Result;
}

private static void CreateApplication()
{
if (Excel != null)
return;
Excel = new Application();
}

public static void LoadBook(string _FileName)
{
if (Book != null)
ReleaseResources();
CreateApplication();
Book = Excel.Workbooks.Open(_FileName);
Sheet = Book.Sheets[1];
}

public static ExcelInfo QueryExcel(string _FileName)
{
try
{
LoadBook(_FileName);
ExcelInfo Result = new ExcelInfo();

Range last = Sheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
Range range = Sheet.get_Range("A1", last);

Result.MaxY = last.Row;
Result.MaxX = last.Column;
return Result;
}
finally
{
ReleaseResources();
}
}

public static string GetCellValue(int _Col, int _Row, bool _AutoTrim = true)
{
if (_AutoTrim)
return Sheet.Cells[_Row, _Col].Value.ToString().Trim(); // _Row, _Col - in this order, indeed!
else
return Sheet.Cells[_Row, _Col].Value.ToString();
}

public static DateTime GetCellValueAsDate(int _Col, int _Row, string _Format)
{
string StringDate = GetCellValue(_Col, _Row, true);
CultureInfo Provider = CultureInfo.InvariantCulture;
DateTime TheDate = DateTime.ParseExact(StringDate, _Format, Provider);
return TheDate;
}

public static void SetCellValue(int _Col, int _Row, string _Value)
{
Sheet.Cells[_Row, _Col].Value = _Value;
}

public static void ReleaseResources()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Book != null)
{
Book.Close();
Marshal.ReleaseComObject(Book);
Book = null;
}
if (Excel != null)
{
Excel.Quit();
Marshal.ReleaseComObject(Excel);
Excel = null;
}
Sheet = null;
}

public static void SaveWorkbook()
{
Book.Save();
}
}

Похожие вопросы