C# 将DataGridView导出成Excel

/// <summary>
        /// 由DataGridView导出
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="sheetName"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ExportToExcel(DataGridView grid, string sheetName = "result",string subtitle="", string filePath = null)
        {
            if (grid.Rows.Count <= 0) return null;

            if (string.IsNullOrEmpty(filePath))
            {
                filePath = GetSaveFilePath();
            }

            if (string.IsNullOrEmpty(filePath)) return null;
            
            bool isCompatible = GetIsCompatible(filePath);

            IWorkbook workbook = CreateWorkbook(isCompatible);
            ICellStyle cellStyle = GetCellStyle(workbook);
            ISheet sheet = workbook.CreateSheet(sheetName);

            sheet.DefaultRowHeight = 25 * 20;
            
            int rowIndex = 2;

            //列名称
            IRow headerRow = sheet.CreateRow(rowIndex);
            int columnsIndex=0;
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                if (grid.Columns[i].Visible)
                {
                    string headerText = (grid.Columns[i].HeaderText == string.Empty) ? grid.Columns[i].Name : grid.Columns[i].HeaderText;                    
                    ICell cell = headerRow.CreateCell(columnsIndex);
                    cell.SetCellValue(headerText);
                    cell.CellStyle = cellStyle;                    
                    columnsIndex++;                    
                }
            }

            //因为有了列数,就可以合并标题行了
            ICell titleCell = sheet.CreateRow(0).CreateCell(0);
            NPOI.SS.Util.CellRangeAddress address = new NPOI.SS.Util.CellRangeAddress(0, 0, 0, columnsIndex - 1);
            sheet.AddMergedRegion(address);

            titleCell.SetCellValue(sheetName);
            ICellStyle titleCellStyle = GetTitleCellStyle(workbook);
            titleCell.CellStyle = titleCellStyle;

            //副标题
            ICell subtitleCell = sheet.CreateRow(1).CreateCell(0);
            NPOI.SS.Util.CellRangeAddress subtitleAddress = new NPOI.SS.Util.CellRangeAddress(1, 1, 0, columnsIndex - 1);
            sheet.AddMergedRegion(subtitleAddress);

            subtitleCell.SetCellValue(subtitle);
            ICellStyle subtitleCellStyle = GetSubTitleCellStyle(workbook);
            subtitleCell.CellStyle = subtitleCellStyle;

            rowIndex++;

            //两个样式
            ICellStyle stringCellStyle = GetBorderCellStyle(workbook);
            stringCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;

            ICellStyle numberCellStyle = GetNumerCellStyle(workbook,"#,##0.00");
            numberCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Right;
            
            //取得数据集
            DataTable dt = (DataTable)grid.DataSource;
            int rn = 0;            
            while (rn<grid.Rows.Count)
            {
                DataGridViewRow row=grid.Rows[rn];

                IRow dataRow = sheet.CreateRow(rowIndex);
                columnsIndex = 0;
                for (int n = 0; n < grid.Columns.Count; n++)
                {
                    if (grid.Columns[n].Visible)
                    {                        
                        stringCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
                        numberCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Right;
                        
                        if (grid.Columns[n].DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
                        {                            
                            stringCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                            numberCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                        }
                        
                        //建立单元格
                        ICell cell = dataRow.CreateCell(columnsIndex);
                        string strValue = (row.Cells[n].Value ?? "").ToString();
                        
                        //数据类型
                        string fieldName = grid.Columns[n].Name;
                        string type = (dt.Columns.Contains(fieldName))?dt.Columns[fieldName].DataType.ToString().ToLower():"string";
                        if (type == "system.decimal")
                        {                            
                            cell.SetCellValue(convertToDouble(strValue));
                            cell.CellStyle = numberCellStyle;
                        }
                        else
                        {                            
                            cell.SetCellValue(strValue);
                            cell.CellStyle = stringCellStyle;
                        }
                        columnsIndex++;
                    } //end if
                } //end for

                rn++;
                rowIndex++;
            }

            //自动列宽
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                sheet.AutoSizeColumn(i);
            }
            
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            workbook.Write(fs);
            fs.Dispose();

            sheet = null;
            headerRow = null;
            workbook = null;

            return filePath;
        }

 

Guess you like

Origin blog.csdn.net/qq_42213965/article/details/101547898