当前位置: 首页 > news >正文

NPOI操作excel

1、基本导出方法

private void ExportToExcel()
        {
            SaveFileDialog sdfExport = new SaveFileDialog();
            sdfExport.Filter = "Excel文件|*.xls";
            if (sdfExport.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string filename = sdfExport.FileName;
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("Student");

            IRow rowHeader = sheet.CreateRow(0);//表头行
            rowHeader.CreateCell(0, CellType.String).SetCellValue("姓名");
            rowHeader.CreateCell(1, CellType.String).SetCellValue("年龄");
            rowHeader.CreateCell(2, CellType.String).SetCellValue("生日");

            //把查询结果导出到Excel
            for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
            {
                Student student = new Student();
                student.StuName = dataGridViewX1.Rows[i].Cells["StuName"].Value.ToString();
                student.StuAge = dataGridViewX1.Rows[i].Cells["StuAge"].Value.ToString();
                student.StuBirthday = dataGridViewX1.Rows[i].Cells["StuBirthday"].Value.ToString();
                IRow row = sheet.CreateRow(i + 1);
                row.CreateCell(0, CellType.String).SetCellValue(student.StuName);
                row.CreateCell(1, CellType.String).SetCellValue(student.StuAge);

                ICellStyle styledate = workbook.CreateCellStyle();
                IDataFormat format = workbook.CreateDataFormat();
                //格式具体有哪些请看单元格右键中的格式,有说明
                styledate.DataFormat = format.GetFormat("yyyy/m/d");

                ICell cellInDate = row.CreateCell(2, CellType.Numeric);
                cellInDate.CellStyle = styledate;
                cellInDate.SetCellValue(student.StuBirthday);
            }

            using (Stream stream = File.OpenWrite(filename))
            {
                workbook.Write(stream);
            }
        }
View Code

2、ExcelUtility

using System;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Windows.Forms;
using System.Drawing;
using CommonHelper;

namespace NPOIOprateExcel
{
    public class ExcelUtility
    {
        /// <summary>
        /// 将excel导入到datatable
        /// </summary>
        /// <param name="filePath">excel路径</param>
        /// <param name="isColumnName">第一行是否是列名</param>
        /// <returns>返回datatable</returns>
        public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
        {
            DataTable dataTable = null;
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本
                    if (filePath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本
                    else if (filePath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);

                    if (workbook != null)
                    {
                        sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
                        dataTable = new DataTable();
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum;//总行数
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行
                                int cellCount = firstRow.LastCellNum;//列数

                                //构建datatable的列
                                if (isColumnName)
                                {
                                    startRow = 1;//如果第一行是列名,则从第二行开始读取
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            if (cell.StringCellValue != null)
                                            {
                                                column = new DataColumn(cell.StringCellValue);
                                                dataTable.Columns.Add(column);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        column = new DataColumn("column" + (i + 1));
                                        dataTable.Columns.Add(column);
                                    }
                                }

                                //填充行
                                for (int i = startRow; i <= rowCount; ++i)
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;

                                    dataRow = dataTable.NewRow();
                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(j);                                        
                                        if (cell == null)
                                        {
                                            dataRow[j] = "";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                            switch (cell.CellType)
                                            {
                                                case CellType.Blank:
                                                    dataRow[j] = "";
                                                    break;
                                                case CellType.Numeric:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
                                                    if (format == 14 || format == 31 || format == 57 || format == 58)
                                                        dataRow[j] = cell.DateCellValue;
                                                    else
                                                        dataRow[j] = cell.NumericCellValue;
                                                    break;
                                                case CellType.String:
                                                    dataRow[j] = cell.StringCellValue;
                                                    break;
                                            }
                                        }
                                    }
                                    dataTable.Rows.Add(dataRow);
                                }
                            }
                        }
                    }
                }
                return dataTable;
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }
        public static string getdatatype(DataTable Table,string colname)
        {
            string datatype=null;
            for (int j = 0; j < Table.Columns.Count; j++)
            {
                if (Table.Columns[j].Caption == colname)
                {
                    datatype = Table.Columns[j].DataType.ToString();
                    break;
                }

            }
            return datatype;
        }

        public int[] Datagridtosql(DevComponents.DotNetBar.Controls.DataGridViewX datagrid, System.Windows.Forms.BindingSource ds)
        {

            int[] rows;

            rows = new int[2];
            rows[0] = 0;
            rows[1] = 0;

            int insert_rows = 0;
            int update_rows = 0;
            int error_rows = 0;
            string[] cdatatype;
            int rowCount = datagrid.Rows.Count;//行数
            int columnCount = datagrid.Columns.Count;//列数

            //设置列头
            int vcount = 0;
            string sql1 = "";
            string insert_sql1 = "";
            string update_sql1 = "";
            string select_sql1 = "";
            DataSet dt = (DataSet)ds.DataSource;
            DataTable Table = dt.Tables[ds.DataMember];
            cdatatype = new string[columnCount];
            for (int c = 0; c < columnCount; c++)
            {
                if (datagrid.Columns[c].Visible)
                {
                    sql1 += datagrid.Columns[c].DataPropertyName + ",";
                }
                cdatatype[c] = getdatatype(Table, datagrid.Columns[c].DataPropertyName);
            }
            sql1 = sql1.Substring(0, sql1.Length - 1);
            sql1 += ")";


            update_sql1 = "update " + ds.DataMember + " set  ";
            select_sql1 = "select count(*) from " + ds.DataMember + " where StuName=";

            for (int i = 0; i < rowCount; i++)
            {

                string select_sql = select_sql1 + "'" + datagrid.Rows[i].Cells[1].Value.ToString() + "'";
                int num = (int)AccessHelper.ExecuteScalar(select_sql, CommandType.Text, null);
                if (num > 0)
                {
                    update_sql1 = "update " + ds.DataMember + " set ";

                    for (int j = 0; j < columnCount; j++)
                    {
                        if (datagrid.Columns[j].Visible)
                        {
                            update_sql1 += "" + datagrid.Columns[j].DataPropertyName + "=";
                            string datatype = cdatatype[j];
                            if (datatype == "System.String")
                            {
                                update_sql1 += "'" + datagrid.Rows[i].Cells[j].Value.ToString() + " ',";
                            }
                            if (datatype == "System.Boolean")
                            {
                                update_sql1 += "" + datagrid.Rows[i].Cells[j].Value.ToString() + ",";
                            }
                            if ((datatype == "System.Int32") || (datatype == "System.Int16") || (datatype == "System.Double"))
                            {
                                update_sql1 += "" + datagrid.Rows[i].Cells[j].Value.ToString() + ",";
                            }

                            if (datatype == "System.DateTime")
                            {
                                if (!string.IsNullOrEmpty(datagrid.Rows[i].Cells[j].Value.ToString()))
                                {
                                    update_sql1 += "#" + datagrid.Rows[i].Cells[j].Value.ToString() + "#,";
                                }
                                else
                                {
                                    update_sql1 += "Null,";
                                }
                            }

                        }

                    }
                    update_sql1 = update_sql1.Substring(0, update_sql1.Length - 1);
                    update_sql1 += " where StuName=" + "'" + datagrid.Rows[i].Cells[1].Value.ToString() + "'"; ;
                    try
                    {
                        AccessHelper.ExecuteQuery(update_sql1, CommandType.Text, null);
                        update_rows++;
                    }
                    catch (Exception e)
                    {
                    }
                }
                else
                {
                    insert_sql1 = "insert into " + ds.DataMember + "(" + sql1;
                    insert_sql1 += "  values(";
                    for (int j = 0; j < columnCount; j++)
                    {
                        if (datagrid.Columns[j].Visible)
                        {
                            // MessageBox.Show(getdatatype(Table, datagrid.Columns[j].DataPropertyName) + datagrid.Columns[j].DataPropertyName);
                            string datatype = cdatatype[j];
                            if (datatype == "System.String")
                            {
                                insert_sql1 += "'" + datagrid.Rows[i].Cells[j].Value.ToString() + " ',";
                            }
                            if (datatype == "System.Boolean")
                            {
                                insert_sql1 += "" + datagrid.Rows[i].Cells[j].Value.ToString() + ",";
                            }
                            if ((datatype == "System.Int32") || (datatype == "System.Int16") || (datatype == "System.Double"))
                            {
                                insert_sql1 += "" + datagrid.Rows[i].Cells[j].Value.ToString() + ",";
                            }

                            if (datatype == "System.DateTime")
                            {
                                if (!string.IsNullOrEmpty(datagrid.Rows[i].Cells[j].Value.ToString()))
                                {
                                    insert_sql1 += "#" + datagrid.Rows[i].Cells[j].Value.ToString() + "#,";
                                }
                                else
                                {
                                    insert_sql1 += "Null,";
                                }
                            }

                        }

                    }
                    insert_sql1 = insert_sql1.Substring(0, insert_sql1.Length - 1);
                    insert_sql1 += ")";
                    try
                    {
                        AccessHelper.ExecuteQuery(insert_sql1, CommandType.Text, null);
                        insert_rows++;
                    }
                    catch (Exception e)
                    {
                    }

                }
            }
            return rows; ;
        }

        public static int ExcelToDatagrid(DevComponents.DotNetBar.Controls.DataGridViewX datagrid, string filePath, bool isColumnName=true)
        {
            FileStream fs = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            char[] delimiterChars = { '.', '\\' };
            string[] Mystr = filePath.Split(delimiterChars);
            string sheetName = Mystr[Mystr.Length - 2]; ;// 没有扩展名的文件名 “Default”
            int[] colarray;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本
                    if (filePath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本
                    else if (filePath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);

                    if (workbook != null)
                    {
                        sheet = workbook.GetSheet(sheetName);//读取第一个sheet,当然也可以循环读取每个sheet
                        //dataTable = new DataTable();
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum;//总行数
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行
                                int cellCount = firstRow.LastCellNum;//列数

                                //构建datatable的列
                                colarray = new int[cellCount];
                                if (isColumnName)
                                {
                                    startRow = 1;//如果第一行是列名,则从第二行开始读取
                                    
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            int columnCount = datagrid.Columns.Count;//列数
                                            for (int j = 0; j < columnCount; ++j)
                                            {
                                                if (cell.StringCellValue == datagrid.Columns[j].HeaderText)
                                                {
                                                    colarray[j] = i;
                                                    break;
                                                }

                                            }

                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        colarray[i] = i;
                                    }
                                }

                                //填充行
                                
                                for (int i = startRow; i <= rowCount; ++i)
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;
                                    datagrid.Rows.Add();

                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(colarray[j]);
                                        if (cell == null)
                                        {
                                            datagrid.Rows[i-1].Cells[j].Value = "";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                            switch (cell.CellType)
                                            {
                                                case CellType.Blank:
                                                    datagrid.Rows[i-1].Cells[j].Value = "";
                                                     break;
                                                case CellType.Numeric:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
                                                    if (format == 14 || format == 31 || format == 57 || format == 58)
                                                        datagrid.Rows[i-1].Cells[j].Value = cell.DateCellValue;
                                                    else
                                                        datagrid.Rows[i-1].Cells[j].Value = cell.NumericCellValue;
                                                    break;
                                                case CellType.String:
                                                    datagrid.Rows[i-1].Cells[j].Value = cell.StringCellValue;
                                                    break;
                                                case CellType.Boolean:
                                                    datagrid.Rows[i - 1].Cells[j].Value = cell.BooleanCellValue;
                                                    break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return 1;
            }
            catch (Exception e)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return -1;
            }
        }


        public static bool DataTableToExcel(DataTable dt,string fileName)
        {
            bool result = false;
            IWorkbook workbook = null;
            FileStream fs = null;
            IRow row = null;
            ISheet sheet = null;
            ICell cell = null;
            char[] delimiterChars = { '.', '\\' };
            string[] Mystr = fileName.Split(delimiterChars);
            string sheetName = Mystr[Mystr.Length - 2];
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    workbook = new HSSFWorkbook();
                    sheet = workbook.CreateSheet(sheetName);//创建一个名称为Sheet0的表
                    int rowCount = dt.Rows.Count;//行数
                    int columnCount = dt.Columns.Count;//列数

                    //设置列头
                    row = sheet.CreateRow(0);//excel第一行设为列头
                    for (int c = 0; c < columnCount; c++)
                    {
                        cell = row.CreateCell(c);
                        cell.SetCellValue(dt.Columns[c].ColumnName);
                    }                    

                    //设置每行每列的单元格,
                    for (int i = 0; i <rowCount; i++)
                    {
                        row = sheet.CreateRow(i+1);
                        for (int j = 0; j < columnCount; j++)
                        {                            
                            cell = row.CreateCell(j);//excel第二行开始写入数据
                            cell.SetCellValue(dt.Rows[i][j].ToString());                            
                        }
                    }
                    using (fs = File.OpenWrite(fileName)) 
                    {
                        workbook.Write(fs);//向打开的这个xls文件中写入数据
                        result = true;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return false;
            }
        }

        public static bool DataGridViewXToExcel(DevComponents.DotNetBar.Controls.DataGridViewX dt,string filename)
        {
            bool result = false;
            IWorkbook workbook = null;
            FileStream fs = null;
            IRow row = null;
            ISheet sheet = null;
            ICell cell = null;
            char[] delimiterChars = { '.', '\\' };
            string[] Mystr = filename.Split(delimiterChars);
            string sheetName = Mystr[Mystr.Length - 2];;// 没有扩展名的文件名 “Default”
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    workbook = new HSSFWorkbook();
                    sheet = workbook.CreateSheet(sheetName);//创建一个名称为Sheet0的表
                    int rowCount = dt.Rows.Count;//行数
                    int columnCount = dt.Columns.Count;//列数

                    //设置列头
                    row = sheet.CreateRow(0);//excel第一行设为列头
                    for (int j = 0; j < columnCount; j++)
                    {
                        if (dt.Columns[j].Visible)
                        {
                            cell = row.CreateCell(j);
                            cell.SetCellValue(dt.Columns[j].HeaderText);
                        }
                    }

                    //设置每行每列的单元格,
                    for (int i = 0; i < rowCount; i++)
                    {   
                        row = sheet.CreateRow(i + 1);
                        for (int j = 0; j < columnCount; j++)
                        {
                            if (dt.Columns[j].Visible)
                            {
                                cell = row.CreateCell(j);//excel第二行开始写入数据
                                cell.SetCellValue(dt.Rows[i].Cells[j].Value.ToString());
                            }
                        }
                    }
                    using (fs = File.OpenWrite(filename))
                    {
                        workbook.Write(fs);//向打开的这个xls文件中写入数据
                        result = true;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return false;
            }
        }
    }
}
View Code

 

转载于:https://www.cnblogs.com/liuslayer/p/5805512.html

相关文章:

  • Spark核心概念
  • Spring MVC+Kaptcha实现验证码功能
  • iOS NSDecimalNumber 使用
  • linux中断处理原理分析
  • 图论1——基础
  • 移动端 Web 开发前端知识整理
  • Javascript 正则校验身份证
  • 理解原型其实是理解原型链
  • Java 中的 GC -- GC基础常识
  • 五分钟搞定 HTTPS 配置,二哥手把手教
  • 5 Maven生命周期和插件
  • 坦克大战--Java类型 ---- (2)按键设置和用户名的输入
  • Ubuntu SSH root 登录 Permission denied 错误
  • nginx版本升级问题
  • 每天学习2小时,17年前端经验分享,让你前端之路不再迷茫
  • 0x05 Python数据分析,Anaconda八斩刀
  • Android Studio:GIT提交项目到远程仓库
  • CentOS 7 防火墙操作
  • Go 语言编译器的 //go: 详解
  • in typeof instanceof ===这些运算符有什么作用
  • JS实现简单的MVC模式开发小游戏
  • laravel 用artisan创建自己的模板
  • node-glob通配符
  • 飞驰在Mesos的涡轮引擎上
  • 基于axios的vue插件,让http请求更简单
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 京东美团研发面经
  • 看图轻松理解数据结构与算法系列(基于数组的栈)
  • 前端
  • 世界上最简单的无等待算法(getAndIncrement)
  • 算法系列——算法入门之递归分而治之思想的实现
  • 微信开放平台全网发布【失败】的几点排查方法
  • 我的面试准备过程--容器(更新中)
  • 小程序button引导用户授权
  • d²y/dx²; 偏导数问题 请问f1 f2是什么意思
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • 智能情侣枕Pillow Talk,倾听彼此的心跳
  • ​如何在iOS手机上查看应用日志
  • #1015 : KMP算法
  • #pragma multi_compile #pragma shader_feature
  • #大学#套接字
  • #微信小程序:微信小程序常见的配置传旨
  • (2)(2.10) LTM telemetry
  • (2022版)一套教程搞定k8s安装到实战 | RBAC
  • (PyTorch)TCN和RNN/LSTM/GRU结合实现时间序列预测
  • (react踩过的坑)antd 如何同时获取一个select 的value和 label值
  • (附源码)计算机毕业设计ssm基于Internet快递柜管理系统
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (译) 理解 Elixir 中的宏 Macro, 第四部分:深入化
  • (转)IIS6 ASP 0251超过响应缓冲区限制错误的解决方法
  • ... 是什么 ?... 有什么用处?
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .gitignore文件---让git自动忽略指定文件
  • .Net 6.0 处理跨域的方式
  • .NET HttpWebRequest、WebClient、HttpClient