Skip to content

Instantly share code, notes, and snippets.

@Mahno74
Last active July 6, 2021 10:37
Show Gist options
  • Save Mahno74/91cacc8a7fb88a0a4d534dde010238cc to your computer and use it in GitHub Desktop.
Save Mahno74/91cacc8a7fb88a0a4d534dde010238cc to your computer and use it in GitHub Desktop.
Export to Exel
//Сначала добавляем сылку на Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Windows;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExpotToExel {
public class Car {
public string Make { get; set; }
public string Color { get; set; }
public string PetName { get; set; }
}
public partial class MainWindow : Window {
List<Car> carsInStock = new List<Car> {
new Car {Color="Green", Make="VW", PetName="Mary"},
new Car {Color="Red", Make="Mersedes", PetName="Melany"},
new Car {Color="Black", Make="BMW", PetName="Horaise"},
new Car {Color="Yellow", Make="Nautilus", PetName="Nemo"}
};
static void ExportToExcel(List<Car> carsInStock) {
//Загружаем Excel и создаем новую пустую книгу
Excel.Application excelApp = new Excel.Application();
//Делаем видимым (не обязательно)
//excelApp.Visible = true;
excelApp.Workbooks.Add();
//Используем одни рабочий лист
Excel._Worksheet workSheet = excelApp.ActiveSheet;
//Устанавливаем заголовки столбцов
workSheet.Cells[1, "A"] = "Make";
workSheet.Cells[1, "B"] = "Color";
workSheet.Cells[1, "C"] = "Pet Name";
//Отображаем все данные из списка в ячейках
int row = 1;
foreach (Car c in carsInStock) {
row++;
workSheet.Cells[row, "A"] = c.Make;
workSheet.Cells[row, "B"] = c.Color;
workSheet.Cells[row, "C"] = c.PetName;
}
//Придать симпатичный вид таблицам
workSheet.Range["A1"].AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);
//Сохранить файл, завершить работу Excel
workSheet.SaveAs($@"{Environment.CurrentDirectory}\Inventory.xlsx");
excelApp.Quit();
}
public MainWindow() {
InitializeComponent();
ExportToExcel(carsInStock);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment