c# 使用 NPOI 导出数据到 Excel 文件中

 internal class NPOIHelper
    {
        internal static bool Export(string fileName, DataTable dtSource, string myDateFormat = "yyyy-MM")
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.FileName = fileName + ".xlsx";
            dialog.DefaultExt = "xlsx";
            dialog.Filter = "Excel文件(*.xls)|*.xlsx";
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return false;
            }
            XSSFWorkbook wb = new XSSFWorkbook();
            ISheet sheet = wb.CreateSheet("Sheet1");
            IRow rowHeader = sheet.CreateRow(0);
            for (int i = 0; i < dtSource.Columns.Count; i++)
            {
                DataColumn column = dtSource.Columns[i];
                rowHeader.CreateCell(i).SetCellValue(column.Caption);
            }

            short decimalformat = HSSFDataFormat.GetBuiltinFormat("0.00");
            short dateformat = wb.CreateDataFormat().GetFormat(myDateFormat);
            ICellStyle styleDecimal = wb.CreateCellStyle();
            styleDecimal.DataFormat = decimalformat;
            ICellStyle styleDate = wb.CreateCellStyle();
            styleDate.DataFormat = dateformat;
            ICellStyle styleNormal = wb.CreateCellStyle();

            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                DataRow dr = dtSource.Rows[i];
                IRow ir = sheet.CreateRow(i + 1);
                for (int j = 0; j < dr.ItemArray.Length; j++)
                {
                    ICell icell = ir.CreateCell(j);
                    object cellValue = dr[j];
                    Type type = cellValue.GetType();
                    if (type == typeof(decimal) || type == typeof(double) || type == typeof(int) || type == typeof(float))
                    {
                        icell.SetCellValue(Convert.ToDouble(cellValue));
                        icell.CellStyle = styleDecimal;
                    }
                    else if (type == typeof(DateTime))
                    {
                        icell.SetCellValue(Convert.ToDateTime(cellValue).ToString(myDateFormat));
                        icell.CellStyle = styleNormal;
                    }
                    else if (type == typeof(bool))
                    {
                        icell.SetCellValue(Convert.ToBoolean(cellValue) ? "" : "");
                        icell.CellStyle = styleNormal;
                    }
                    else
                    {
                        icell.SetCellValue(cellValue.ToString());
                        icell.CellStyle = styleNormal;
                    }
                }
            }

            using (FileStream fs = File.OpenWrite(dialog.FileName))
            {
                wb.Write(fs);
            }
            return true;
        }
    }

 

posted @ 2022-06-17 09:38  echo三毛  阅读(752)  评论(0编辑  收藏  举报