C# excel导入导出,NOPI ,简单例子

 

C# 发现用NOPI 来对excel文件的导入导出,比较方便实用:


using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utility;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
 

namespace AloneSell
{
    public  class ExcelFile
    {
        //引用方法:选中项目,右键-管理NuGet程序包,搜索npoi,安装npoi

        #region Excel导入
        /// <summary>
        /// Excel导入:读取excel文档数据到DataTable
        /// </summary>
        /// <param name="path">excel文档路径</param>
        /// <param name="isheet">要读取的工作表索引,为空=0</param>
        /// <returns>DataTable</returns>
        public  DataTable Excel_Import(string path,int? isheet)
        {
          
            DataTable dt = new DataTable();
         
            using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                #region
                string extension = Path.GetExtension(path).ToLower();
                IWorkbook workbook;
                if (extension == ".xlsx")
                {
                    workbook = new XSSFWorkbook(fsRead);
                }
                else
                {
                    workbook = new HSSFWorkbook(fsRead);
                }
                if (isheet == null) { isheet = 0; }
                ISheet sheet = workbook.GetSheetAt((int)isheet);
                IRow currentRow = sheet.GetRow(0);

                //最后一个方格的编号 即总的列数
                int cellCount = currentRow.LastCellNum;

                for (int i = 0; i < cellCount; i++)
                {
                    //DataColumn dc = new DataColumn();
                    dt.Columns.Add(currentRow.GetCell(i).ToString());//增加列
                }
                #endregion

                for (int j = 0; j <= sheet.LastRowNum - 1; j++)
                {

                    dt.Rows.Add();//增加行
                    IRow currentRow1 = sheet.GetRow(j + 1);
                    if (currentRow1 != null)
                    {
                        #region
                        for (int c = 0; c < currentRow1.LastCellNum; c++)
                        {

                            ICell cell = currentRow1.GetCell(c);
                            if (cell == null || cell.CellType == CellType.Blank)
                            {
                                dt.Rows[j][c] = DBNull.Value;
                            }
                            else
                            {
                                //如果当前单元格不为空,则根据单元格的类型获取数据
                                switch (cell.CellType)
                                {
                                    //只有当单元格的数据类型是数字类型的时候使用cell.NumericCellValue来获取值。其余类型都使用字符串来获取.日期类型数据插入单元格后也是CellType.NUMERIC
                                    case CellType.Numeric:
                                        //cell.NumericCellValue;
                                        dt.Rows[j][c] = cell.NumericCellValue;
                                        break;
                                    default:
                                        //cell.ToString();
                                        dt.Rows[j][c] = cell.ToString();
                                        break;
                                }
                            }
                           
                        }
                        #endregion
                    }
                }
                workbook.Close();
                return dt;
            }
            #region 例子
            /*
            try
            {
                OpenFileDialog openFile = new OpenFileDialog();
                openFile.Filter = "excel2003|*.xls|excel|*.xlsx";
                openFile.InitialDirectory = Application.StartupPath;
                if (openFile.ShowDialog() == DialogResult.OK)
                {
                    string fileName = openFile.FileName;
                    ExcelFile _excel = new ExcelFile();
                    DataTable table = _excel.Excel_Import(fileName,0);
                    //将数据存储到数据库中...
                    Pub.ShowInfo("导入excel数据成功");
                }
            }
            catch (Exception ex)
            {
                Pub.ShowInfo(ex.Message);
            } 
             */
            #endregion
        }
        #endregion

        #region Excel导出
        /// <summary>
        /// 导出到excel文档中 
        /// </summary>
        /// <param name="source">数据源:DataGridView、DataTable</param>
        /// <param name="path">excel文档路径</param>
        /// <param name="sheetName">保存数据的工作表名</param>
        /// <returns>1=成功;其他=getCode(return)</returns>
        public  int Excel_Export(object source, string path,string sheetName)
        {

            #region 判断数据源
            DataGridView dgv = null;
            DataTable table = null;
            int iDataType = 0;//数据源格式:0=DataGridView;1=DataTable;
            if (source is DataGridView)
            {
                dgv = (DataGridView)source;
                iDataType = 0;
                if (dgv.Rows.Count < 1)
                {
                    Message = "要导出的数据为空,无法导出";
                    return -2;
                }
            }
            else if (source is DataTable)
            {
                table = (DataTable)source;
                iDataType = 1;
                if (table == null || table.Rows.Count < 1)
                {
                    Message = "要导出的数据为空,无法导出";
                    return -2;
                }
            }
            else if (source is DataSet)
            {
                DataSet ds = ((DataSet)source);
                if (ds == null || ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1)
                {
                    Message = "要导出的数据为空,无法导出";
                    return -2;
                }
                table = ds.Tables[0];
                iDataType = 1;
            }
            else
            {
                Message = "导出失败,数据源source只支持DataTabel,DataGridView";
                return -1;
            }
            #endregion

            #region  导出excel
            string extension = Path.GetExtension(path).ToLower();
            IWorkbook workbook;
            if (extension == ".xlsx")
            {
                workbook = new XSSFWorkbook();
            }
            else
            {
                workbook = new HSSFWorkbook();
            }
            sheetName = sheetName.Trim() == "" ? "sheet1" : sheetName;
            ISheet sheet = workbook.CreateSheet(sheetName);
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
            {
                IRow row_Head = sheet.CreateRow(0);

                if (iDataType == 0)
                {
                    #region 数据源是DataGridView
                    int icellIndex = 0;
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        if (!dgv.Columns[i].Visible)
                        {
                            continue;
                        }
                        ICell cell = row_Head.CreateCell(icellIndex);
                        icellIndex++;
                        cell.SetCellValue(dgv.Columns[i].HeaderText);
                    }

                    for (int i = 0; i < dgv.Rows.Count; i++)
                    {

                        icellIndex = 0;
                        IRow row1 = sheet.CreateRow(i + 1);
                        for (int j = 0; j < dgv.Columns.Count; j++)
                        {
                            if (!dgv.Columns[j].Visible)
                            {
                                continue;
                            }

                            ICell cell = row1.CreateCell(icellIndex);
                            icellIndex++;
                            if (dgv.Rows[i].Cells[j].Value == null)
                                cell.SetCellValue("");
                            else
                                cell.SetCellValue(dgv.Rows[i].Cells[j].Value.ToString().Trim());
                        }
                    }
                    #endregion
                }
                else
                {
                    #region 数据源是DataTable
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        ICell cell = row_Head.CreateCell(i);
                        cell.SetCellValue(table.Columns[i].ColumnName);
                    }

                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        IRow row1 = sheet.CreateRow(i + 1);
                        for (int j = 0; j < table.Columns.Count; j++)
                        {
                            ICell cell = row1.CreateCell(j);
                            if (table.Rows[i][j] == null)
                                cell.SetCellValue("");
                            else
                                cell.SetCellValue(table.Rows[i][j].ToString().Trim());
                        }
                    }
                    #endregion
                }

                workbook.Write(fs);
                workbook.Close();
            }
            #endregion

            Message = "成功将数据导出到 " + path;
            return 1;

            #region 例子
            /*
            //可以先判断数据源,是否有数据
            ..........................
            //导出Excel
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.DefaultExt = "xls";
            saveFileDialog1.Filter = "excel2003|*.xls|excel|*.xlsx";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (saveFileDialog1.FileName != "")
                {
                    try
                    {
                        //1 = 成功;其他 = getCode(return)
                        //DataTable table = (DataTable)dataGridView1.DataSource;
                        ExcelFile _excel = new ExcelFile();
                        int iexcel = _excel.Excel_Export(dataGridView1, saveFileDialog1.FileName);//table
                        if (iexcel == 1)
                            Pub.ShowInfo("成功将数据导出到" + saveFileDialog1.FileName);
                        else
                            Pub.ShowInfo(_excel.getCode(iexcel));
                    }
                    catch (Exception ex)
                    { Pub.ShowWarning(ex.Message); }
                }
            }
            */
            #endregion
        }

        #endregion

        public  string getCode(int iCode)
        {
            string msg = "导出数据成功";
            switch(iCode)
            {
                case -2:
                    {
                        msg = "要导出的数据为空,无法导出";
                        break;
                    }
                case -1:
                    {
                        msg = "导出失败,数据源source只支持DataTabel,DataGridView";
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            return msg;
        }

        #region 为了兼容原来的方法,实际还是兼容不了

        /// <summary>
        /// 为了兼容原来的方法
        /// </summary>
        /// <param name="source"></param>
        /// <param name="fileName"></param>
        public  void DataGridViewToExcel(object source,string fileName)
        {
            Excel_Export(source, fileName, "");
        }
        /// <summary>
        /// 为了兼容原来的方法
        /// </summary>
        /// <param name="source"></param>
        /// <param name="fileName"></param>
        public  void DataGridViewToExcel(object source, string fileName,string sheetName)
        {
            Excel_Export(source, fileName, sheetName);
        }
        public delegate void MessageChange(string msg);
        public  event MessageChange OnMessageChange;
        private  string _Message = "";
        public  string Message
        {
            get { return _Message; }
            set
            {
                _Message = value;
                if (OnMessageChange != null)
                {
                    OnMessageChange(value);
                }
            }
        }
        #endregion
    }


}
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值