Bài này một số đoạn code lấy data, người viết dùng Entity Framework Core để lấy dữ liệu.
Sử dụng package EPPlus
Mở cửa sổ Manage Nuget Package để cài:
hoặc có thể gõ lệnh cài: Install-Package EPPlus
Giả sử export data từ DataGridView, chúng ta viết lệnh như sau:
// Button click event to export DataGridView to Excel
private void btnExportToExcel_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Excel Files|*.xlsx";
saveFileDialog.Title = "Save as Excel File";
saveFileDialog.FileName = "ExportedData.xlsx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
ExportToExcel(dataGridView1, saveFileDialog.FileName);
MessageBox.Show("Data successfully exported to Excel!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
else
{
MessageBox.Show("No data available to export!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void ExportToExcel(DataGridView dgv, string filePath)
{
ExcelPackage.License.SetNonCommercialPersonal("My Name");
using (ExcelPackage excel = new ExcelPackage())
{
// Create a worksheet
ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Sheet1");
// Add the headers
for (int i = 0; i < dgv.Columns.Count; i++)
{
worksheet.Cells[1, i + 1].Value = dgv.Columns[i].HeaderText;
}
// Add the rows
for (int i = 0; i < dgv.Rows.Count; i++)
{
for (int j = 0; j < dgv.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1].Value = dgv.Rows[i].Cells[j].Value?.ToString();
}
}
// Save the file
FileInfo excelFile = new FileInfo(filePath);
excel.SaveAs(excelFile);
}
}
Thiết lập license theo hướng dẫn (nếu có): https://epplussoftware.com/en/Home/GettingStartedCommunityLicense
Thiết kế report cho hóa đơn. Dữ liệu truyền vào là mã hóa đơn, dữ liệu truyền ra là mẫu hóa đơn bán lẻ thông thường.
Mẫu hóa đơn: https://www.meinvoice.vn/tin-tuc/21871/mau-hoa-don-ban-le/
Chỉnh sửa theo mẫu template bên dưới:
Một số gợi ý:
int maHD = 10248; // Giả sử mã hóa đơn truyền vào là 10248
QlbanHangContext ctx = new QlbanHangContext();
var fullPath = Path.Combine(Application.StartupPath, "Hoa-don-ban-hang-template.xlsx"); //giả sử file template Hoa-don-ban-hang-template.xlsx đặt cùng chỗ chương trình chạy
FileInfo path = new FileInfo(fullPath);
if (path.Exists)
{
ExcelPackage.License.SetNonCommercialPersonal("My Name");
using (ExcelPackage p = new ExcelPackage(path))
{
ExcelWorksheet ws = p.Workbook.Worksheets["Sheet1"];
// Lấy thông tin hóa đơn
var ttHoaDon = ctx.HoaDons.Include(x => x.MaKhNavigation).SingleOrDefault(x => x.MaHd == maHD);
ws.Cells["A4"].Value = $"Tên khách hàng: {ttHoaDon.MaKhNavigation.TenCty}";
ws.Cells["A5"].Value = $"Địa chỉ: {ttHoaDon.MaKhNavigation.DiaChi}";
// Lấy thông tin chi tiết hóa đơn
var invData = ctx.ChiTietHoaDons.Where(x => x.MaHd == maHD)
.Select(x => new
{
x.MaSpNavigation.TenSp,
x.SoLuong,
x.MaSpNavigation.DonGia,
ThanhTien = x.MaSpNavigation.DonGia * x.SoLuong
}).ToList();
//chèn số dòng đúng với số lượng sản phẩm mua
ws.InsertRow(9, invData.Count - 1);
//Set số thứ tự
ws.Cells[$"A8:A{8 + invData.Count - 1}"].FillNumber(x => x.StartValue = 1);
ws.Cells[$"C{8 + invData.Count}"].Formula = $"=SUM(C8:C{8 + invData.Count - 1})";
ws.Cells[$"E{8 + invData.Count}"].Formula = $"=SUM(E8:E{8 + invData.Count - 1})";
for (int i = 0; i < invData.Count; i++)
{
ws.Cells[8 + i, 1].Value = (i + 1).ToString();
ws.Cells[8 + i, 2].Value = invData[i].TenSp;
ws.Cells[8 + i, 3].Value = invData[i].SoLuong;
ws.Cells[8 + i, 4].Value = invData[i].DonGia;
ws.Cells[8 + i, 5].Value = invData[i].ThanhTien;
}
p.SaveAs($"INV{maHD}.xlsx"); // có thể đổi tên file
}
}