C#NPOI调用EXCEL导入方法

使用方法:
1. 本方法使用的取出excel使用的方法是一个叫NPOL的using包下的方法,在网上有许多用法除了可以excel导入导出外,还可以多doc,ppt做操作,有兴趣可以自行研究这个方法。
案例包下载:链接:http://pan.baidu.com/s/1slm1DEH 密码:mcju
npol使用手册:链接:http://pan.baidu.com/s/1slU0WY5 密码:bggv
NPOI官方网站:http://npoi.codeplex.com/
可以到此网站上去下载最新的NPOI组件版本。

2. 案例包使用方法(有一个案例包):

private void btnImport_Click(object sender, EventArgs e)
        {
            InitializeWorkbook(@"C:\Users\Administrator\Desktop\零售加盟系统\xxxxx.xls"); //这一步操作,是为了打开excel进去到里面去控制它。
            ConvertToDataTable(27);//这一个方法就是调用excel的方法,这里参数表示,要读取的列数ps:暂时还未找到让它自己识别最后一列的方法

            dataGridView1.DataSource = dataSet1.Tables[0];

            
            
        }

完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
namespace ImportXlsToDataTable
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        NPOI.SS.UserModel.IWorkbook hssfworkbook;
        void InitializeWorkbook(string path)
        {

            string fileExt = Path.GetExtension(path); //返回指定的路径字符串的扩展名
            using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))  //打开EXCLE文件的方法
            {
                if (fileExt == ".xls")
                {
                    hssfworkbook = new HSSFWorkbook(file);
                }
                else if (fileExt == ".xlsx")
                {
                    hssfworkbook = new XSSFWorkbook(file);
                }
            }
        }

        void ConvertToDataTable(int count) //这里参数表示,要读取的列数。ps:暂时还未找到让它自己识别最后一列的方法
        {
            ISheet sheet = hssfworkbook.GetSheetAt(0); //在Excel文档中,第一张工作表的缺省索引是0
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();//获得某一个Sheet的所有IRow

            DataTable dt = new DataTable();
            for (int j = 0; j <= count; j++)//给DataTable添加列名
            {
                //dt.Columns.Add(Convert.ToChar(((int)'A')+j).ToString());
                dt.Columns.Add("F"+j );
            }

            while (rows.MoveNext())//循环完所以数据行
            {
                IRow row = (IRow)rows.Current;//当前行的所有单元格
                DataRow dr = dt.NewRow();//实例化一个新的数据行

                for (int i = 0; i < row.LastCellNum; i++)//LastCellNum最后一行行标,比行数小1
                {
                    ICell cell = (ICell)row.GetCell(i);//读取当前行的第I个单元格


                    if (cell == null)
                    {
                        dr[i] = null;
                    }
                    else
                    {
                        dr[i] = cell.ToString();
                    }
                }
                dt.Rows.Add(dr);
               
            }
            dataSet1.Tables.Add(dt);
            //for (int i = 0; i <= dt.Rows.Count - 1; i++)
            //{
            //    // for (int j = 0; j < 11; j++)
            //    //  {

            //    String Content = dt.Rows[i]["A"].ToString().Trim();
            //    Console.WriteLine("{0}", Content);

            //    // }
            //}
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            InitializeWorkbook(@"C:\Users\Administrator\Desktop\零售加盟系统\C1JSW201702B1.xls");
            ConvertToDataTable();

            dataGridView1.DataSource = dataSet1.Tables[0];

            
            
        }

        //switch(cell.CellType)
        //{
        //    case HSSFCellType.BLANK:
        //        dr[i] = "[null]";
        //        break;
        //    case HSSFCellType.BOOLEAN:
        //        dr[i] = cell.BooleanCellValue;
        //        break;
        //    case HSSFCellType.NUMERIC:
        //        dr[i] = cell.ToString();    //This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number.
        //        break;
        //    case HSSFCellType.STRING:
        //        dr[i] = cell.StringCellValue;
        //        break;
        //    case HSSFCellType.ERROR:
        //        dr[i] = cell.ErrorCellValue;
        //        break;
        //    case HSSFCellType.FORMULA:
        //    default:
        //        dr[i] = "="+cell.CellFormula;
        //        break;
        //}
    }
}

4.原理方面:
个人理解,这个方法体对excel的操作也是逐列的每一个单元格一个一个的读取。除了可以做这个外还可以往excel写入数据。Npol这个using有着对excel极大的操作,是目前兼容性最高的方法不需要用户去装载任何东西,哪怕用户没有装excel这个软件。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Excel文件中的数据导入到Oracle数据库可以使用以下步骤: 1. 首先,需要将Excel文件读取到C#中,可以使用NPOI库来读取Excel文件中的数据。 2. 连接Oracle数据库,并打开连接。 3. 创建一个OracleCommand对象,该对象用于执行SQL命令。 4. 遍历Excel文件中的每一行数据,并将数据插入到Oracle数据库中,可以使用OracleCommand对象的ExecuteNonQuery方法来执行SQL语句。 以下是一个示例代码: ```csharp using System; using System.Data; using System.Data.OracleClient; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; // 读取Excel文件 HSSFWorkbook workbook = new HSSFWorkbook(new FileStream("Excel文件路径", FileMode.Open)); ISheet sheet = workbook.GetSheetAt(0); // 连接Oracle数据库 string connectionString = "Data Source=数据库地址;User ID=用户名;Password=密码;"; OracleConnection connection = new OracleConnection(connectionString); connection.Open(); // 创建OracleCommand对象 OracleCommand command = new OracleCommand(); command.Connection = connection; // 遍历Excel文件中的每一行数据,将数据插入到Oracle数据库中 for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row == null) continue; string col1 = row.GetCell(0).ToString().Trim(); string col2 = row.GetCell(1).ToString().Trim(); string col3 = row.GetCell(2).ToString().Trim(); string sql = "insert into table_name(col1, col2, col3) values(:col1, :col2, :col3)"; command.CommandText = sql; command.Parameters.Clear(); command.Parameters.Add(new OracleParameter(":col1", col1)); command.Parameters.Add(new OracleParameter(":col2", col2)); command.Parameters.Add(new OracleParameter(":col3", col3)); command.ExecuteNonQuery(); } // 关闭连接 connection.Close(); ``` 需要注意的是,在执行SQL语句时,使用了参数化查询,可以防止SQL注入攻击。另外,需要根据Excel文件和Oracle数据库的实际情况,修改代码中的表名、列名和连接字符串等信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值