csharp: Export or Import excel using NPOI



excel 2003:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using NPOI;
using NPOI.HSSF.UserModel; //excel 2003
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;

namespace NPOIExcelDemo
{

    /// <summary>
    ///
    /// </summary>
    public partial class Form3 : Form
    {
        string extractFile = Environment.CurrentDirectory + @"\Sample.xls";
        string result = Environment.CurrentDirectory + @"\result1.xls";

        /// <summary>
        ///
        /// </summary>
        public Form3()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 涂聚文
        /// 20150730
        /// EXCEL 2003
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form3_Load(object sender, EventArgs e)
        {
            try
            {
                //两个文件的标题和内容要相同,所以数据都变成了字符型的 excel 2003
                string file1 = Environment.CurrentDirectory + @"\20150728工资结构.xls";
                string file2 = Environment.CurrentDirectory + @"\工资结构.xls";
                DataTable dt = new DataTable();
                string[] files = new string[] { file1, file2 };
                for (int i = 0; i < files.Length; i++)
                {
                    MergeData(files[i], dt);
                }
                ExportDataTableToExcel(dt, result);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        #region
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <param name="dt"></param>
        private static void MergeData(string extractFile, DataTable dt)
        {
            if (!File.Exists(extractFile))
            {
                MessageBox.Show(string.Format("Excel File '{0}' to extract is not found (Current Directory: {1}).", extractFile, Environment.CurrentDirectory));
                return;
            }
            // write data in workbook from xls document.
            StreamReader input = new StreamReader(extractFile);
            IWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(input.BaseStream));
            ///
            foreach (HSSFSheet sheetname in workbook)
            {
                string s = sheetname.SheetName;  //获取工作表名称
            }

            // read the current table data
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(1);//第二个工作表
            // read the current row data
            HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
            // LastCellNum is the number of cells of current rows
            int cellCount = headerRow.LastCellNum;

            if (dt.Rows.Count == 0)
            {

                // build header for there is no data after the first implementation
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    // get data as the column header of DataTable
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);

                    dt.Columns.Add(column);
                }
            }
            else
            {

                // TODO: check if the subsequent sheet corresponds
            }
            // LastRowNum is the number of rows of current table
            int rowCount = sheet.LastRowNum + 1;
            for (int i = (sheet.FirstRowNum + 1); i < rowCount; i++)
            {
                HSSFRow row = (HSSFRow)sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                        // get data and convert them into character string type, then save them into the rows of datatable
                        dataRow[j] = row.GetCell(j).ToString(); //要判断不同的数据类型

                }
                dt.Rows.Add(dataRow);
            }
            workbook = null;
            sheet = null;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="strFileName"></param>
        public static void ExportDataTableToExcel(DataTable dtSource, string strFileName)
        {
            // create workbook XSSF
            HSSFWorkbook workbook = new HSSFWorkbook();
            // the table named mySheet
            HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("mySheet");
            // create the first row
            HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0);
            foreach (DataColumn column in dtSource.Columns)
            {
                // create the cells in the first row, and add data into these cells circularly
                dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

            }
            //create rows on the basis of data from datatable(not including table header), and add data into cells in every row
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dataRow = (HSSFRow)sheet.CreateRow(i + 1);
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString()); //要判断不同的数据类型
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {

                    workbook.Write(fs);// write mySheet table in xls document and save it
                }
            }
        }
        #endregion
    }
}

excel 2007,2010

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using NPOI;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; //excel 2007

namespace NPOIExcelDemo
{

    /// <summary>
    ///
    /// </summary>
    public partial class Form1 : Form
    {
        string extractFile = Environment.CurrentDirectory + @"\Sample.xls";
        string result = Environment.CurrentDirectory + @"\result.xls";
        /// <summary>
        ///
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 涂聚文
        /// 20150730
        /// EXCEL 2007
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //两个文件的标题和内容要相同,所以数据都变成了字符型的 excel 2007
                string file1 = Environment.CurrentDirectory + @"\20150728工资结构.xlsx";
                string file2 = Environment.CurrentDirectory + @"\工资结构.xlsx";
                DataTable dt = new DataTable();
                string[] files = new string[] { file1, file2 };
                for (int i = 0; i < files.Length; i++)
                {
                    MergeData(files[i], dt);
                }
                ExportDataTableToExcel(dt, result);
            }
            catch (Exception ex)
            {
              MessageBox.Show(ex.Message.ToString());
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <param name="dt"></param>
        private static void MergeData(string path, DataTable dt)
        {
            // write data in workbook from xls document.
            XSSFWorkbook workbook = new XSSFWorkbook(path);
            ///
            foreach (XSSFSheet sheetname in workbook)
            {
               string s= sheetname.SheetName;
            }
            // read the current table data
            XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(1);//第二个工作表
            // read the current row data
            XSSFRow headerRow = (XSSFRow)sheet.GetRow(0);
            // LastCellNum is the number of cells of current rows
            int cellCount = headerRow.LastCellNum;

            if (dt.Rows.Count == 0)
            {

                // build header for there is no data after the first implementation
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    // get data as the column header of DataTable
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);

                    dt.Columns.Add(column);
                }
            }
            else
            {

                // TODO: check if the subsequent sheet corresponds
            }
            // LastRowNum is the number of rows of current table
            int rowCount = sheet.LastRowNum + 1;
            for (int i = (sheet.FirstRowNum + 1); i < rowCount; i++)
            {
                XSSFRow row = (XSSFRow)sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                        // get data and convert them into character string type, then save them into the rows of datatable
                        dataRow[j] = row.GetCell(j).ToString();

                }
                dt.Rows.Add(dataRow);
            }
            workbook = null;
            sheet = null;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="strFileName"></param>
        public static void ExportDataTableToExcel(DataTable dtSource, string strFileName)
        {
            // create workbook
            XSSFWorkbook workbook = new XSSFWorkbook();
            // the table named mySheet
            XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("mySheet");
            // create the first row
            XSSFRow dataRow = (XSSFRow)sheet.CreateRow(0);
            foreach (DataColumn column in dtSource.Columns)
            {
                // create the cells in the first row, and add data into these cells circularly
                dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

            }
            //create rows on the basis of data from datatable(not including table header), and add data into cells in every row
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dataRow = (XSSFRow)sheet.CreateRow(i + 1);
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {

                    workbook.Write(fs);// write mySheet table in xls document and save it
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="dataFormatter"></param>
        /// <param name="formulaEvaluator"></param>
        /// <returns></returns>
        private static string GetValue(ICell cell, DataFormatter dataFormatter, IFormulaEvaluator formulaEvaluator)
        {
            string ret = string.Empty;
            if (null == cell) { return ret; }
            ret = dataFormatter.FormatCellValue(cell, formulaEvaluator);
            return ret.Replace("\n", " "); // remove line break
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string GetComment(ICell cell)
        {
            string ret = string.Empty;
            if ((null == cell) || (null == cell.CellComment)) { return ret; }
            IRichTextString str = cell.CellComment.String;
            if (str != null && str.Length > 0)
            {
                ret = str.ToString();
            }
            return ret.Replace("\n", " "); // remove line break
        }
    }
}
时间: 2024-08-04 03:53:05

csharp: Export or Import excel using NPOI的相关文章

csharp: Export or Import excel using MyXls

 excel 2003 (效果不太理想) using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using org.in2bits.MyXls; using org.in2bits.

csharp: Export DataSet into Excel and import all the Excel sheets to DataSet

/// <summary> /// Export DataSet into Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form3_Load(object sender, EventArgs e) { //Create an Emplyee Dat

use export and import move ZPOOL&#039;s underdev from one machine to another OR upgrade a zfs version OR recover destroyed pools

前面我们介绍了zfs的pool, 类似LVM. 由多个块设备组成. 如果这些块设备要从一个机器转移到另一台机器的话, 怎么实现呢? zfs通过export和import来实现底层块设备的转移. 在已有POOL的主机上, 先将会读写POOL或dataset的正在运行的程序停止掉, 然后执行export. 执行export会把cache flush到底层的块设备, 同时卸载dataset和pool. import时, 可能需要指定块设备的目录, 但是并不需要指定顺序. 例如 : [root@spar

详解免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)_实用技巧

很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel报表,并且在后台调用Microsoft Excel ActiveX更有效率;从Office文档中提取文本,以帮助您实现全文索引功能(大多数时候,此功能用于创建搜索引擎): 从Office文档提取图像: 生成包含公式的Excel工作表.  一.NPOI组件概述: NPOI是完全免费使用: 涵盖Exce

Oracle Export and Import简介

1.Export/Import的用处&http://www.aliyun.com/zixun/aggregation/37954.html">nbsp; Oracle Export/Import工具用于在数据库之间 传递数据.  Export从数据库中导出数据到dump文件中  Import从dump文件中到入数据导数据库中  下面是一般使用他们的情况  (1).两个数据库之间传送数据  同一个版本的oracle Server之间  不同版本的oracle Server之间  同种

使用datapump 导出导入同义词(export and import synonym using datapump)

      对于同义词的备份我们有多种方式来实现,如直接通过脚本生成同义词的创建脚本,或者使用dbms_metadata.get_ddl来提取同义词的定义脚本.然而在使用传统的exp或是datapump expdp实现schema级别数据迁移时,不能导出公共同义词.尽管如此,我们依旧可以使用导出导入的方式来实现.所不同的是,我们使用FULL=Y的方式来单独导出同义词,然后再将其导入的目标数据库.下文是对此进行的描述,末尾也给出了手动创建同义词的脚本.   1.环境 --源数据库 SQL> sel

C# 使用 NPOI 库读写 Excel 文件

原文:C# 使用 NPOI 库读写 Excel 文件 NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼容 xls 和 xlsx.官网提供了一份 Examples,给出了很多应用场景的例子,打包好的二进制文件类库,也仅有几MB,使用非常方便. 读Excel NPOI 使用 HSSFWorkbook 类来处理 xls,XSSFWorkbook 类来处理 xlsx,它们都继承接口 IWorkbook,因此可以通过

Docker export import containers, save load images, commit containers, docker images tree

本文讨论一下与docker镜像相关的几个接口. 制作镜像相关 :  使用dockerfile制作一个sshd镜像 http://blog.163.com/digoal@126/blog/static/1638770402014102711413675/ 从container制作镜像(使用docker commit) http://blog.163.com/digoal@126/blog/static/1638770402014923112924656/ 制作base镜像 http://blog.

db2 import/export tool

原文 http://www.cnblogs.com/mac_arthur/archive/2011/08/21/2147846.html Contents- 使用db2 backup指令备份- 使用db2 restore指令恢复- 使用db2look提取数据库结构DDL- 用于数据移动的文件格式- 使用db2move导出全部数据- 使用db2 export指令导出数据- 使用db2move导入(import)数据- 使用db2 import指令导入数据 使用db2 backup指令备份 首先关闭