winform method for exporting dataviewgrid data as excel
- 2020-12-18 01:54:07
- OfStack
This article gives an example of how winform exports dataviewgrid data as excel. Share to everybody for everybody reference. Specific implementation methods are as follows:
#region export dataViewGrid The data in the view is xls format
private void btnExportList_Click(object sender, EventArgs e)
{
string fname = string.Empty;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = " Table files |*.xls";
sfd.DefaultExt = "xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
fname = sfd.FileName;
}
else
{
return;
}
// Export the current dataGridView All data to xls file
//1. Inbound file , new lib Folder, copy related files
//2. Add pairs to your project dll A reference to the
//3. Set up in memory excel Table files
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet(" The first 1 page ");
// Create header
HSSFRow title = sheet.CreateRow(0);
title.CreateCell(0).SetCellValue(" Serial number ");
title.CreateCell(1).SetCellValue(" The name ");
title.CreateCell(2).SetCellValue(" gender ");
title.CreateCell(3).SetCellValue(" age ");
title.CreateCell(4).SetCellValue(" address ");
title.CreateCell(5).SetCellValue(" The phone ");
title.CreateCell(6).SetCellValue(" birthday ");
for (int rowindex = 0; rowindex < dgvStudens.RowCount; rowindex++)
{
// Create the first 1 line
HSSFRow row = sheet.CreateRow(rowindex + 1);
for (int colindex = 0; colindex < dgvStudens.Rows[rowindex].Cells.Count; colindex++)
{
row.CreateCell(colindex).SetCellValue((dgvStudens.Rows[rowindex].Cells[colindex].Value == null) ? null : dgvStudens.Rows[rowindex].Cells[colindex].Value.ToString());
}
//// Create the first 1 The first 1 column
//HSSFCell cell = row.CreateCell(0);
//cell.SetCellType(3);
//cell.SetCellValue(dgvStudens.Rows[rowindex].Cells[0].Value.ToString());
//// The first 1 Line first 2 column
//row.CreateCell(1).SetCellValue(dgvStudens.Rows[rowindex].Cells[1].Value.ToString());
//// The first 1 Line first 3 column
//row.CreateCell(2).SetCellValue(dgvStudens.Rows[rowindex].Cells[2].Value.ToString());
//// The first 1 Line first 4 column ,age It might be empty
//// row.CreateCell(3).SetCellValue(dgvStudens.Rows[0].Cells[3].Value.ToString());
//row.CreateCell(3).SetCellValue((dgvStudens.Rows[rowindex].Cells[3].Value == null) ? null : dgvStudens.Rows[rowindex].Cells[3].Value.ToString());
}
using (FileStream fs = new FileStream(fname, FileMode.Create))
{
workbook.Write(fs);
}
;
}
#endregion
Hopefully this article has helped you with your C# programming.