public static bool ExportToExcel(System.Windows.Forms.DataGridView dgv, string path, string templatePath = null, bool exportHiddenColumns = false)
{
bool result = true
IWorkbook workbook = null
bool hasTemplate = false
if (!string.IsNullOrEmpty(templatePath) && File.Exists(templatePath = commonHelper.StartupPath + "\\" + templatePath))
{
//File.Copy(templatePath, path, true)
hasTemplate = true
FileStream fileStream = new FileStream(templatePath, FileMode.Open, FileAccess.Read)
if (path.EndsWith(".xlsx")) // 2007版本
workbook = new XSSFWorkbook(fileStream)
else
//if (path.EndsWith(".xls")) // 2003版本
workbook = new HSSFWorkbook(fileStream)
}
else
{
if (path.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook()
else
//if (path.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook()
}
var headerStyle = workbook.CreateCellStyle()
var cellStyle = workbook.CreateCellStyle()
headerStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center
headerStyle.VerticalAlignment = VerticalAlignment.Center
//HSSFFont font1 = hssfworkbook.CreateFont()
var font = workbook.CreateFont()
font.IsBold = true
var cellfont = workbook.CreateFont()
cellfont.FontName = "宋体"
headerStyle.SetFont(font)
headerStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin
headerStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin
headerStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin
headerStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin
cellStyle.SetFont(cellfont)
var sheet = hasTemplate ? workbook.GetSheetAt(0) : workbook.CreateSheet()
var startRowIndex = sheet.LastRowNum
var columnIndex = 0
if (!hasTemplate)
{
var row = sheet.CreateRow(startRowIndex)
for (int i = 0
{
if (!exportHiddenColumns && !dgv.Columns[i].Visible)
continue
var cell = row.CreateCell(columnIndex)
cell.CellStyle = headerStyle
sheet.SetColumnWidth(columnIndex, dgv.Columns[i].Width * 35)
cell.SetCellValue(dgv.Columns[i].HeaderText)
columnIndex++
}
}
startRowIndex++
for (int i = 0
{
columnIndex = 0
var row = sheet.CreateRow(startRowIndex)
for (int j = 0
{
if (!exportHiddenColumns && !dgv.Columns[j].Visible)
continue
var cell = row.CreateCell(columnIndex)
cell.CellStyle = cellStyle
cell.SetCellValue(dgv[j, i].FormattedValue?.ToString() ?? "")
columnIndex++
}
startRowIndex++
}
using (var file = new FileStream(path, FileMode.Create))
{
workbook.Write(file)
}
return result
}