MainWindow.xaml:
<Button Content="Export to Excel" Command="{Binding ExportExcelCommand}"></Button>
Tạo thư mục ViewModel, trong thư mục ViewModel, tạo class MainViewModel
MainViewModel.cs
private ObservableCollection<ProfileActor> _Profiles;
public ObservableCollection<ProfileActor> Profiles { get=>_Profiles; set { _Profiles = value;OnPropertyChanged(); } }
public MainViewModel()
{
ExportExcelCommand=new RelayCommand<object>((p)=>true, (p) => { ExportExcel(p); });
}
public ICommand ExportExcelCommand { get; set; }
private void ExportExcel(object p)
{
string filePath = "";
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Excel | *.xlsx | Excel 2003 | *.xls";
if (dialog.ShowDialog() == true)
{
filePath = dialog.FileName;
}
if (string.IsNullOrEmpty(filePath))
{
MessageBox.Show("Đường dẫn báo cáo không hợp lệ");
return;
}
try
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage x = new ExcelPackage())
{
x.Workbook.Properties.Author ="Đức";
x.Workbook.Properties.Title = "Add data";
x.Workbook.Worksheets.Add("Add data sheet");
ExcelWorksheet ws = x.Workbook.Worksheets[0];
ws.Name = "Add data sheet";
ws.Cells.Style.Font.Size = 11;
ws.Cells.Style.Font.Name = "Calibri";
string[] arrColumnHeader = {
"STT"
"Họ tên",
"Năm sinh"
};
var countColHeader = arrColumnHeader.Count();
ws.Cells[1, 1].Value = "Add data";
ws.Cells[1, 1, 1, countColHeader].Merge = true;
ws.Cells[1, 1, 1, countColHeader].Style.Font.Bold = true;
ws.Cells[1, 1, 1, countColHeader].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
int colIndex = 1;
int rowIndex = 2;
foreach (var item in arrColumnHeader)
{
var cell = ws.Cells[rowIndex, colIndex];
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
cell.Value = item;
colIndex++;
}
foreach (var item in Profiles)
{
colIndex = 1;
rowIndex++;
ws.Cells[rowIndex, colIndex++].Value = item.Id;
ws.Cells[rowIndex, colIndex++].Value = item.Birthday.ToShortDateString();
ws.Cells[rowIndex, colIndex++].Value = item.Name;
}
Byte[] bin = x.GetAsByteArray();
File.WriteAllBytes(filePath, bin);
}
MessageBox.Show("Xuất excel thành công!");
}
catch (Exception EE)
{
MessageBox.Show("Có lỗi khi lưu file!");
}
}
Trong Folder ViewModel, tạo thêm 1 class BaseViewModel
BaseViewModel.cs
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
class RelayCommand<T> : ICommand
{
private readonly Predicate<T> _canExecute;
private readonly Action<T> _execute;
public RelayCommand(Predicate<T> canExecute, Action<T> execute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_canExecute = canExecute;
_execute = execute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute((T)parameter);
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}