/// <summary>
/// 将列表数据导出到excel(使用NPOI第三方组件)
/// 生成.xls文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="dgv"></param>
public static void ExportExcel(string fileName, DataGridView dgv)
{
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
DialogResult dia = saveDialog.ShowDialog();
if (dia != DialogResult.OK)
{
return;
}
saveFileName = saveDialog.FileName;
//1、得到所有的可见列,并按照可见顺序排序
Dictionary<string, int> dictColNameDispIdx = new Dictionary<string, int>();
foreach (DataGridViewColumn col in dgv.Columns)
{
if (col.Visible)
{
dictColNameDispIdx.Add(col.Name, col.DisplayIndex);
}
}
dictColNameDispIdx = dictColNameDispIdx.OrderBy(o => o.Value).ToDictionary(o => o.Key, p => p.Value);
int idxRow = 0;//行索引
int idxCol = 0;//列索引
HSSFWorkbook workbook = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1");
//2、标题行
NPOI.SS.UserModel.IRow excelRow = sheet.CreateRow(idxRow);
foreach (KeyValuePair<string, int> kvp in dictColNameDispIdx)
{
NPOI.SS.UserModel.ICell cell = excelRow.CreateCell(idxCol );
cell.SetCellValue(dgv.Columns[kvp.Key].HeaderText);
}
idxRow ;//
//3、数据行
for (int i = 0; i < dgv.Rows.Count; i )
{
excelRow = sheet.CreateRow(idxRow i);
idxCol = 0;//列复位
foreach (KeyValuePair<string, int> kvp in dictColNameDispIdx)
{
if (dgv.Rows[i].Cells[kvp.Key].Value != null)
{
NPOI.SS.UserModel.ICell cell = excelRow.CreateCell(idxCol );
cell.SetCellValue(dgv.Rows[i].Cells[kvp.Key].Value.ToString());
}
}
}
//4、冻结首行
sheet.CreateFreezePane(0, 1, 0, 1);
try
{
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
FileStream file = new FileStream(saveFileName, FileMode.Create);
workbook.Write(file);
file.Close();
workbook = null;
ms.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(saveFileName "保存失败:" ex.Message, "提示", MessageBoxButtons.OK);
return;
}
MessageBox.Show(saveFileName " 保存成功", "提示", MessageBoxButtons.OK);
}
评论