NPOI将Excel中的数据导入到数据库

    using(FileStream fs=File.OpenRead(@"d:/MY.xls"))
            {
                IWorkbook wk = new HSSFWorkbook(fs);
                if (wk.NumberOfSheets>0)
                {
                    ISheet sheet = wk.GetSheetAt(0);
                    for (int i = 0; i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);

                        // //Id, Name, ParentID
                        //string name=row.GetCell(1).CellType==CellType.STRING.StringCellValue;
                        string Name = row.GetCell(1).StringCellValue == "null" ? null : row.GetCell(1).StringCellValue;
                        int? ParentID = row.GetCell(2) == null ? null:(int?) row.GetCell(2).NumericCellValue;

                        string sql = "insert into TreeView values( @Name, @ParentID)";

                        SqlParameter[] pms = new SqlParameter[]{
                        new SqlParameter("@Name",Name==null?DBNull.Value:(object)Name),
                        new SqlParameter("@ParentID",ParentID==null?DBNull.Value:(object)ParentID)

                        };
                        SqlHelper.ExecteNonQuery(System.Data.CommandType.Text, sql, pms);
                    }
                }

            }

  public class DoExcel
    {

        public static void LogeToExcel(string[] strs)
        {
            DateTime dt = DateTime.Now;
            string dir = "/ApiLogs/" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
            string path = HttpContext.Current.Server.MapPath(dir);
            int rowNum = 0;
            if (!File.Exists(path))
            {
                //Directory.CreateDirectory(path);
                //创建一个workbook
                IWorkbook wk = new HSSFWorkbook();
                //创建sheet
                ISheet sh = wk.CreateSheet("Sheet1");
                IRow row = sh.CreateRow(rowNum);
                for (int i = 0; i < strs.Length; i++)
                {
                    ICell iCell = row.CreateCell(i);
                    iCell.SetCellValue(strs[i]);
                }

                using (FileStream fs = File.OpenWrite(path))
                {
                    wk.Write(fs);
                }
            }
            else
            {
                FileStream fss = File.OpenRead(path);
                IWorkbook wk = new HSSFWorkbook(fss);
                int InsertRowIndex = wk.GetSheetAt(0).LastRowNum+1;
                ExportExcelByTemple(strs, path, path, 20, InsertRowIndex);
            }
        }

        /// <summary>
        /// 用模板导出Excel
        /// </summary>
        /// <param name="table"></param>
        /// <param name="strFileName">导出路径</param>
        /// <param name="templetPath">模板路径</param>
        /// <param name="startRow">从第几行开始写数据,从1开始</param>
        public static void ExportExcelByTemple(string[] strs, string strFileName, string templetPath, int rowHeight, int startRow)
        {
            try
            {
                HSSFWorkbook workbook = getWorkBook(templetPath);
                ISheet sheet = getSheet(workbook);
                writeData(workbook, sheet, strs, strFileName, rowHeight, startRow);
                saveData(workbook, strFileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 解析Excel模板,返回WorkBook
        /// </summary>
        /// <param name="templetPath"></param>
        /// <returns></returns>
        private static HSSFWorkbook getWorkBook(string templetPath)
        {
            FileStream file = new FileStream(templetPath, FileMode.Open, FileAccess.Read);
            HSSFWorkbook workbook = new HSSFWorkbook(file);
            return workbook;
        }

        /// <summary>
        /// 返回Sheet
        /// </summary>
        /// <param name="workbook"></param>
        /// <returns></returns>
        private static ISheet getSheet(HSSFWorkbook workbook)
        {
            return workbook.GetSheetAt(0);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="sheet"></param>
        /// <param name="dtSource"></param>
        /// <param name="strFileName"></param>
        /// <param name="rowHeight"></param>
        /// <param name="startRow"></param>
        /// <param name="size"></param>
        private static void writeData(HSSFWorkbook workbook, ISheet sheet, string[] strs, string strFileName, int rowHeight, int startRow)
        {
            // //填充表头
            IRow dataRow = new HSSFRow();
            //填充内容
            dataRow = sheet.CreateRow(startRow);
            dataRow.Height = (short)(rowHeight * 20);
            for (int j = 0; j < strs.Length; j++)
            {
                string drValue = strs[j];
                dataRow.CreateCell(j).SetCellValue(drValue);
            }
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="strFileName"></param>
        private static void saveData(HSSFWorkbook workbook, string strFileName)
        {
            //保存
            using (MemoryStream ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(fs);
                }
            }
        }
    }

向已有的Excel中添加一条信息

  

时间: 2024-07-29 20:04:22

NPOI将Excel中的数据导入到数据库的相关文章

如何把Excel中的数据导入到数据库

NPOI: using NPOI.HSSF.UserModel; using NPOI.SS.Formula.Eval; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Data; using System.IO; namespace ZZAS.HNYZ.GPSInstallManage.Common { public class ExcelHelper : IDisposable {

把excel中的数据导入到数据库中的通用方法

方法/步骤 对于把大量数据存放到数据库中,最好是用图形化数据库管理工具,可是如果没有了工具,只能执行命令的话这会是很费时间的事.那我们只能对数据进行组合,把数据组成insert语句然后在命令行中批量直行即可.   我们对下面数据进行组合,这用到excel中的一个功能. 在excel中有个fx的输入框,在这里把组好的字符串填上去就好了. 注:字符串1 & A2 &字符串2 & ... A2可以直接输入,也可以用鼠标点对应的单元格.   每个字符串之间用 & 符号进行连接.下面

把excel中的数据导入到数据库

import.php <?php header("Content-Type:text/html;charset=utf-8"); echo '<html> <body> <form action="import.php" method="post" enctype="multipart/form-data"> <label for="file">File

SpringMVC框架简单实现上传Excel文件,并将Excel中的数据导入mySQL数据库

第一步 配置DispathcherServlet文件 第二步 配置applicationContext文件 第三步 在index.jsp中 第四步 在HelloSpringmvc.java中写入方法 第五步:与数据库进行连接 第六步 mySQL实体类 第七步 操作excel表 第八步 Dao文件 第九步 测试

Excel中的数据导入到SqlServer数据库中

从SqlServer2008才开始支持导出表结构的和表中的数据,而SqlServer2008以前的数据库只支持导出表结构,有些时候我们可能需要把2008以前的数据库中的数据导出来,这个时候我们可以使用折中的方法,先把数据库导出到Excel中,再把Excel中的数据导入到数据库中(如果两台数据库服务器之间可以互通的话,可以直接建立远程链接进行数据传输,不用如此麻烦), 将SqlServer中的数据导出到Excel中比较简单,这里不再贴图,下面是把Excel中的数据导入到SqlServer中步骤:

使用Python将Excel中的数据导入到MySQL

使用Python将Excel中的数据导入到MySQL 工具 Python 2.7 xlrd MySQLdb 安装 Python 对于不同的系统安装方式不同,Windows平台有exe安装包,Ubuntu自带.使用前请使用下面的命令确保是2.7.x版本: python --version xlrd : 这是一个扩Python包,可以使用pip包管理工具安装:pip install xlrd MySQLdb 为MySQL 的Python驱动接口包,可以到http://sourceforge.net/

用Toad把excel中的数据导入数据库的表中

第1步:找到菜单选项 第2步:选择表名 第3步:选择文件类型为Excel 第4步:设置参数 在oracle中trim函数可以除去字符串前后的空格,所以选上. 第5步:把excel中的列和数据库中的字段对应起来.每一列对应一个字段. 第6步:查看约束 第7步:设置导入模式,我设置的时导入完成后不提交,手动提交. 点击Execute执行. 执行过程中: 出现以下错误,问到是否继续执行.这种错误一般是因为excel中的数据结构与数据库表中的数据类型不统一而引起的. 我点击的yes继续执行,中间可能还会

详解用Navicat工具将Excel中的数据导入Mysql中

第一步:首先需要准备好有数据的excel: 第二步:选择"文件"->"另存为",保存为"CSV(逗号分隔)(*.csv)",将excel表另存为csv文档  第三步:(很重要):如果你的数据中有中文,那么需要将CSV文件处理一下,负责会导入失败:用editplus或者其他编辑器(另存时可以选择保存编码的编辑器)打开CSV文件,然后另存为,选择utf-8(你的数据库也是utf-8哦),点击保存. 第四步:开始导入了,使用mysql图形化工具(

sqlserver怎么将excel表的数据导入到数据库中

在数据库初始阶段,我们有些数据在EXCEL中做好之后,需要将EXCEL对应列名(导入后对应数据库表的字段名),对应sheet(改名为导入数据库之后的表名)导入指定数据库, 相当于导入一张表的整个数据.导入之前需要检查是否存在同名的表,导入的数据表以"$"结尾就是为了避免表重复,以作区分.下面就来看看具体操作步骤. 1 打开SQL Server Management Studio,按图中的路径进入导入数据界面. 2 导入的时候需要将EXCEL的文件准备好,不能打开.点击下一步. 数据源: