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
}
}
}

  

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

  1. csharp: Export or Import excel using MyXls,Spire.Xls

    excel 2003 (效果不太理想) using System; using System.Collections.Generic; using System.ComponentModel; usi ...

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

    /// <summary> /// Export DataSet into Excel /// </summary> /// <param name="send ...

  3. csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net

    //https://www.microsoft.com/en-us/download/details.aspx?id=5124 Open XML SDK 2.0 for Microsoft Offic ...

  4. Import Excel void (NPOI)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  5. ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 try.dot.net 的正确使用姿势 .Net NPOI 根据excel模板导出excel、直接生成excel .Net NPOI 上传excel文件、提交后台获取excel里的数据

    ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案   ASP.NET Core 从2.2版本开始,采用了一个新的名为Endpoint的路由方案,与原来的方案在使用上差别不 ...

  6. ASP.NET导出Excel(利用NPOI和EPPlus库,无需安装Office)

    网上提供了很多Asp.net中操作Excel的方法,其中大部分是调用微软的Office组件,下面提供三个无须安装Office即可从Asp.net输出Excel的方法. 1 简单方法 //下面代码输出的 ...

  7. NetSuite SuiteScript 2.0 export data to Excel file(xls)

    In NetSuite SuiteScript, We usually do/implement export data to CSV, that's straight forward: Collec ...

  8. export和import实现模块化

    export和import实现模块化 阅读目录 ES6的模块化的基本规则或特点: 下面列出几种import和export的基本语法: ES6导入的模块都是属于引用: 循环依赖的问题: 浏览器兼容: 参 ...

  9. 【从翻译mos文章】不再用par file如果是,export or import 包含大写和小写表名称表

    不再用par file如果是,export or import 包含大写和小写表名称表 参考原始: How to Export or Import Case Sensitive Tables With ...

随机推荐

  1. webpack 打包时到底如何组织js

    问题一:引入前端库,方法也是不一样的 比如 lodash.js ,作为一个 chunk 用 html-webpack-plugin 打包到页面里,会生成一个全局变量 window._ ,在其它 js ...

  2. ubuntu14.04LTS安装vmware10.0.1

    因为所用Ubuntu系统是32位,而VMware最新版本又不支持32位,只好下载以前版本vmware10.0.1. vmware10.0.1下载地址:  http://down.it168.com/1 ...

  3. 关于u-boot中的.balignl 16,0xdeadbeef的理解

    .globl _start  //不占内存_start: b       start_code //占4字节内存 ldr pc, _undefined_instruction //占4字节内存 ldr ...

  4. Ubuntu 14.04 安装nVidia驱动后不能进入图形界面的恢复过程

    想要解决Ubuntu14.04的风扇不停的转的问题.由于ubuntu本身不支持双显卡切换,导致集显独显都处于开启状态,发热量和耗电量居高不下. 1. 安装驱动过程 参考[1]中的步骤,做了如下的操作. ...

  5. MTNET 自用ios网络库开源

    短短两天就在https://git.oschina.net/gangwang/MTNET这里收获15个星 github 5星, 值得收藏! MTNET 自用ios网络库开源, 自用很久了,在数歀上架的 ...

  6. cmd窗口编码方式的修改

    cmd默认的编码是采用GBK   regedit HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe\CodePage 十进制:936 GB ...

  7. Android关联源码support-v4的问题解决

    如果在有用到过viewpager或者fragmentActivity等一些v4包下的类,当我们按F3时无法查看到源码,这个时候就需要我们关联该源码,该源码的关联与android源码的关联不一样. 大家 ...

  8. 各种字符串Hash函数比较(转)

    常用的字符串Hash函数还有ELFHash,APHash等等,都是十分简单有效的方法.这些函数使用位运算使得每一个字符都对最后的函数值产生影响.另外还有以MD5和SHA1为代表的杂凑函数,这些函数几乎 ...

  9. @media 手机与IPAD与PC

    @media screen and (min-width: 769px) { bindCard{height:28.5em} } @media screen and (min-device-width ...

  10. 【翻译】C# Tips & Tricks: Weak References - When and How to Use Them

    原文:C# Tips & Tricks: Weak References - When and How to Use Them Sometimes you have an object whi ...