码迷,mamicode.com
首页 > 其他好文 > 详细

使用NPOI导入导出Execl

时间:2015-03-06 21:59:59      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

  .Net中对Execl实际操作中,如果如果直接调用微软的Office组件,会碰到各种问题,为了避免这些问题发生,使用NPOI控件。这是款非常不错的第三方插件。

  在项目中需要引用NPOI.dll文件,这个文件在网上下载一个就可以了。

  NPOI教程链接:http://www.npoi.info/tutorial

  下面是对DataGridView的导入和导出

  导出 

技术分享
/// <summary>
        /// 订单导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportBtn_Click(object sender, EventArgs e)
        {
            //打开一个对话框,选择或输入保存excel文件的地址  
            SaveFileDialog sdfExport = new SaveFileDialog();
            sdfExport.Filter = "Excel文件|*.xls";
            if (sdfExport.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            //获取excel文件名  
            string fileName = sdfExport.FileName;
            //创建一个workbook  
            HSSFWorkbook workbook = new HSSFWorkbook();
            //设置工作表名  
            ISheet sheet = workbook.CreateSheet("采购订单");

            //创建表头行  
            IRow rowHeader = sheet.CreateRow(0);
            //给每个单元格设值  
            rowHeader.CreateCell(0, CellType.STRING).SetCellValue("规格型号");
            rowHeader.CreateCell(1, CellType.STRING).SetCellValue("光度");
            rowHeader.CreateCell(2, CellType.STRING).SetCellValue("散光度");
            rowHeader.CreateCell(3, CellType.STRING).SetCellValue("轴度");
            rowHeader.CreateCell(4, CellType.STRING).SetCellValue("物料英文名");
            rowHeader.CreateCell(5, CellType.STRING).SetCellValue("物料中文名");
            rowHeader.CreateCell(6, CellType.STRING).SetCellValue("在库数量");
            rowHeader.CreateCell(7, CellType.STRING).SetCellValue("在途数量");
            rowHeader.CreateCell(8, CellType.STRING).SetCellValue("理论库存");
            rowHeader.CreateCell(9, CellType.STRING).SetCellValue("月出货数量");
            rowHeader.CreateCell(10, CellType.STRING).SetCellValue("理论周转");
            rowHeader.CreateCell(11, CellType.STRING).SetCellValue("标准周转");
            rowHeader.CreateCell(12, CellType.STRING).SetCellValue("订单数量");
            rowHeader.CreateCell(13, CellType.STRING).SetCellValue("赠品数量");
            rowHeader.CreateCell(14, CellType.STRING).SetCellValue("订单金额");

            //循环dataGridView取出每一条数据(如果是集合或数组,操作一样)  
            for (int i = 0; i < this.gvShow.Rows.Count; i++)
            {
                //循环列  
                for (int j = 0; j < this.gvShow.ColumnCount; j++)
                {
                    //开始创建内容行并放入数据  
                    IRow row = sheet.CreateRow(i + 1);
                    row.CreateCell(0, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[0].Value.ToString());
                    row.CreateCell(1, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[1].Value.ToString());
                    if (this.gvShow.Rows[i].Cells[2].Value != null)
                    {
                        row.CreateCell(2, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[2].Value.ToString());
                    }
                    if (this.gvShow.Rows[i].Cells[3].Value != null)
                    {
                        row.CreateCell(3, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[3].Value.ToString());
                    }
                    row.CreateCell(4, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[4].Value.ToString());
                    row.CreateCell(5, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[5].Value.ToString());
                    row.CreateCell(6, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[6].Value.ToString());
                    row.CreateCell(7, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[7].Value.ToString());
                    row.CreateCell(8, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[8].Value.ToString());
                    row.CreateCell(9, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[9].Value.ToString());
                    row.CreateCell(10, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[10].Value.ToString());
                    row.CreateCell(11, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[11].Value.ToString());
                    row.CreateCell(12, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[12].Value.ToString());
                    row.CreateCell(13, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[13].Value.ToString());
                    row.CreateCell(14, CellType.STRING).SetCellValue(this.gvShow.Rows[i].Cells[14].Value.ToString());
                }

            }
            //保存数据  
            using (Stream stream = File.OpenWrite(fileName))
            {
                workbook.Write(stream);
                MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
View Code

  导入

技术分享
        /// <summary>  
        /// 订单导入
        /// </summary>  
        /// <param name="strFileName">Excel文件全路径(服务器路径)</param>  
        /// <param name="SheetIndex">要获取数据的工作表序号(从0开始)</param>  
        /// <param name="HeaderRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        private void btnImport_Click(object sender, EventArgs e)
        {
            //条件重置
            this.gvShow.Rows.Clear();

            OpenFileDialog importDialog = new OpenFileDialog();
            if (importDialog.ShowDialog() == DialogResult.OK)
            {
                string strFileName = importDialog.FileName.ToString(); //获得文件路径
                using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
                {
                    IWorkbook workbook = new HSSFWorkbook(file);
                    string SheetName = workbook.GetSheetName(0);
                    DataTable dt = RenderDataTableFromExcel(workbook, SheetName, 0);

                    foreach (DataRow item in dt.Rows)
                    {
                        DataGridViewRow Row = new DataGridViewRow();
                        int index = gvShow.Rows.Add(Row);
                        gvShow.Rows[index].Cells[0].Value = item["规格型号"].ToString();
                        gvShow.Rows[index].Cells[1].Value = item["光度"].ToString();
                        gvShow.Rows[index].Cells[2].Value = item["散光度"].ToString();
                        gvShow.Rows[index].Cells[3].Value = item["轴度"].ToString();
                        gvShow.Rows[index].Cells[4].Value = item["物料英文名"].ToString();
                        gvShow.Rows[index].Cells[5].Value = item["物料中文名"].ToString();
                        gvShow.Rows[index].Cells[6].Value = item["在库数量"].ToString();
                        gvShow.Rows[index].Cells[7].Value = item["在途数量"].ToString();
                        gvShow.Rows[index].Cells[8].Value = item["理论库存"].ToString();
                        gvShow.Rows[index].Cells[9].Value = item["月出货数量"].ToString();
                        gvShow.Rows[index].Cells[10].Value = item["理论周转"].ToString();
                        gvShow.Rows[index].Cells[11].Value = item["标准周转"].ToString();
                        gvShow.Rows[index].Cells[12].Value = item["订单数量"].ToString();
                        gvShow.Rows[index].Cells[13].Value = item["赠品数量"].ToString();
                        gvShow.Rows[index].Cells[14].Value = item["订单金额"].ToString();
                    }
                }
                MessageBox.Show("导入成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
View Code
技术分享
        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="workbook">要处理的工作薄</param>  
        /// <param name="SheetName">要获取数据的工作表名称</param>  
        /// <param name="HeaderRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(IWorkbook workbook, string SheetName, int HeaderRowIndex)
        {
            ISheet sheet = workbook.GetSheet(SheetName);
            DataTable table = new DataTable();
            try
            {
                IRow headerRow = sheet.GetRow(HeaderRowIndex);
                int cellCount = headerRow.LastCellNum;
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                    table.Columns.Add(column);
                }
                int rowCount = sheet.LastRowNum;
                #region 循环各行各列,写入数据到DataTable
                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = table.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        ICell cell = row.GetCell(j);
                        if (cell == null)
                        {
                            dataRow[j] = null;
                        }
                        else
                        {
                            //dataRow[j] = cell.ToString();  
                            switch (cell.CellType)
                            {
                                case CellType.BLANK:
                                    dataRow[j] = null;
                                    break;
                                case CellType.BOOLEAN:
                                    dataRow[j] = cell.BooleanCellValue;
                                    break;
                                case CellType.NUMERIC:
                                    dataRow[j] = cell.ToString();
                                    break;
                                case CellType.STRING:
                                    dataRow[j] = cell.StringCellValue;
                                    break;
                                case CellType.ERROR:
                                    dataRow[j] = cell.ErrorCellValue;
                                    break;
                                case CellType.FORMULA:
                                default:
                                    dataRow[j] = "=" + cell.CellFormula;
                                    break;
                            }
                        }
                    }
                    table.Rows.Add(dataRow);
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                table.Clear();
                table.Columns.Clear();
                table.Columns.Add("出错了");
                DataRow dr = table.NewRow();
                dr[0] = ex.Message;
                table.Rows.Add(dr);
                return table;
            }
            finally
            {
                //sheet.Dispose();  
                workbook = null;
                sheet = null;
            }
            #region 清除最后的空行
            for (int i = table.Rows.Count - 1; i > 0; i--)
            {
                bool isnull = true;
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (table.Rows[i][j] != null)
                    {
                        if (table.Rows[i][j].ToString() != "")
                        {
                            isnull = false;
                            break;
                        }
                    }
                }
                if (isnull)
                {
                    table.Rows[i].Delete();
                }
            }
            #endregion
            return table;
        }
View Code

  

使用NPOI导入导出Execl

标签:

原文地址:http://www.cnblogs.com/wuxiaohui/p/4319264.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!