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();//表头行
rowHeader.CreateCell(, CellType.String).SetCellValue("姓名");
rowHeader.CreateCell(, CellType.String).SetCellValue("年龄");
rowHeader.CreateCell(, CellType.String).SetCellValue("生日"); //把查询结果导出到Excel
for (int i = ; 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 + );
row.CreateCell(, CellType.String).SetCellValue(student.StuName);
row.CreateCell(, CellType.String).SetCellValue(student.StuAge); ICellStyle styledate = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
//格式具体有哪些请看单元格右键中的格式,有说明
styledate.DataFormat = format.GetFormat("yyyy/m/d"); ICell cellInDate = row.CreateCell(, CellType.Numeric);
cellInDate.CellStyle = styledate;
cellInDate.SetCellValue(student.StuBirthday);
} using (Stream stream = File.OpenWrite(filename))
{
workbook.Write(stream);
}
}

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 = ;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > )
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > )
workbook = new HSSFWorkbook(fs); if (workbook != null)
{
sheet = workbook.GetSheetAt();//读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > )
{
IRow firstRow = sheet.GetRow();//第一行
int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列
if (isColumnName)
{
startRow = ;//如果第一行是列名,则从第二行开始读取
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 + ));
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 == || format == || format == || format == )
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 = ; 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[];
rows[] = ;
rows[] = ; int insert_rows = ;
int update_rows = ;
int error_rows = ;
string[] cdatatype;
int rowCount = datagrid.Rows.Count;//行数
int columnCount = datagrid.Columns.Count;//列数 //设置列头
int vcount = ;
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 = ; c < columnCount; c++)
{
if (datagrid.Columns[c].Visible)
{
sql1 += datagrid.Columns[c].DataPropertyName + ",";
}
cdatatype[c] = getdatatype(Table, datagrid.Columns[c].DataPropertyName);
}
sql1 = sql1.Substring(, sql1.Length - );
sql1 += ")"; update_sql1 = "update " + ds.DataMember + " set ";
select_sql1 = "select count(*) from " + ds.DataMember + " where StuName="; for (int i = ; i < rowCount; i++)
{ string select_sql = select_sql1 + "'" + datagrid.Rows[i].Cells[].Value.ToString() + "'";
int num = (int)AccessHelper.ExecuteScalar(select_sql, CommandType.Text, null);
if (num > )
{
update_sql1 = "update " + ds.DataMember + " set "; for (int j = ; 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(, update_sql1.Length - );
update_sql1 += " where StuName=" + "'" + datagrid.Rows[i].Cells[].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 = ; 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(, insert_sql1.Length - );
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 = ;
char[] delimiterChars = { '.', '\\' };
string[] Mystr = filePath.Split(delimiterChars);
string sheetName = Mystr[Mystr.Length - ]; ;// 没有扩展名的文件名 “Default”
int[] colarray;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > )
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > )
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 > )
{
IRow firstRow = sheet.GetRow();//第一行
int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列
colarray = new int[cellCount];
if (isColumnName)
{
startRow = ;//如果第一行是列名,则从第二行开始读取 for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
int columnCount = datagrid.Columns.Count;//列数
for (int j = ; 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-].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-].Cells[j].Value = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == || format == || format == || format == )
datagrid.Rows[i-].Cells[j].Value = cell.DateCellValue;
else
datagrid.Rows[i-].Cells[j].Value = cell.NumericCellValue;
break;
case CellType.String:
datagrid.Rows[i-].Cells[j].Value = cell.StringCellValue;
break;
case CellType.Boolean:
datagrid.Rows[i - ].Cells[j].Value = cell.BooleanCellValue;
break;
}
}
}
}
}
}
}
}
return ;
}
catch (Exception e)
{
if (fs != null)
{
fs.Close();
}
return -;
}
} 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 - ];
try
{
if (dt != null && dt.Rows.Count > )
{
workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet(sheetName);//创建一个名称为Sheet0的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数 //设置列头
row = sheet.CreateRow();//excel第一行设为列头
for (int c = ; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
} //设置每行每列的单元格,
for (int i = ; i <rowCount; i++)
{
row = sheet.CreateRow(i+);
for (int j = ; 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 - ];;// 没有扩展名的文件名 “Default”
try
{
if (dt != null && dt.Rows.Count > )
{
workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet(sheetName);//创建一个名称为Sheet0的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数 //设置列头
row = sheet.CreateRow();//excel第一行设为列头
for (int j = ; j < columnCount; j++)
{
if (dt.Columns[j].Visible)
{
cell = row.CreateCell(j);
cell.SetCellValue(dt.Columns[j].HeaderText);
}
} //设置每行每列的单元格,
for (int i = ; i < rowCount; i++)
{
row = sheet.CreateRow(i + );
for (int j = ; 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;
}
}
}
}

NPOI操作excel的更多相关文章

  1. NPOI操作Excel辅助类

    /// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...

  2. NPOI操作excel之写入数据到excel表

    在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...

  3. C#开发中使用Npoi操作excel实例代码

    C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Exce ...

  4. 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数

    2.4.1 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数   NPOI教程:http://www.cnb ...

  5. C# 如何使用NPOI操作Excel以及读取合并单元格等

    C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...

  6. 用NPOI操作EXCEL-锁定列CreateFreezePane()

    public void ExportPermissionRoleData(string search, int roleStatus) { var workbook = new HSSFWorkboo ...

  7. .NET 通过 NPOI 操作 Excel

    目录 .NET 通过 NPOI 操作 Excel 第一步:通过 NuGet 获取 NPOI 包并引入程序集 第二步:引入 NPOI 帮助类 第三步:在程序中调用相应的方法对数据进行导出导入操作 将 D ...

  8. 2.6.2 用NPOI操作EXCEL--设置密码才可以修改单元格内容

    2.6.2 用NPOI操作EXCEL--设置密码       有时,我们可能需要某些单元格只读,如在做模板时,模板中的数据是不能随意让别人改的.在Excel中,可以通过“审阅->保护工作表”来完 ...

  9. 使用NPOI操作Excel文件及其日期处理

    工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...

  10. C#通过NPOI操作Excel

    参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...

随机推荐

  1. Xcode磁盘空间大清理

    我的设备是Macbook Air 13' Mid 2011,128G SSD.最近开始有些存储压力了,用Clean My Mac清理一部分旧文件后,决定对Xcode动手. 移除对旧设备的支持 影响:可 ...

  2. 对《神奇的C语言》文中例子 5 代码的分析讨论

    在春节前,我曾经参与在<神奇的C语言>一文中的例子(5)的讨论,但限于评论内容的有限,现在本文再次对这个问题单独讨论.(此问题原貌,详见<神奇的C语言>,这里我将原文中的代码稍 ...

  3. StackPanel在增加控件的问题

    今天遇到这样一个问题,就是我做了一个自定义控件.然后加到StackPanel中, <StackPanel Height="676" HorizontalAlignment=& ...

  4. fw: webdriver 那些坑

    http://www.cnblogs.com/huang0925/p/3384596.html 使用WebDriver遇到的那些坑   在做web项目的自动化端到端测试时主要使用的是Selenium ...

  5. 如何生成JavaAPI doc

    1         准备工作 1.1    填写完整的注释 对需要生成API的类,填写完整的注释,包括类注释,方法注释,具体格式如下: 类注释: 原先可能author是作者,需要修改成author英文 ...

  6. 期待许久的事情终于发生-微软收购Xamarin

    刚在VS推送的新闻中看到了醒目的标题:Microsoft to acquire Xamarin and empower more developers to build apps on any dev ...

  7. QTP操作excel文档

    对于QTP操作excel的大前提是,保证组建服务里的DCOM配置里存在 microsoft excel application ,具体的查看方式是,在运行框中输入dcomcnfg,然后会打开组件服务的 ...

  8. hbase 协处理器

    一.服务端1.安装Protobuf2.RPC proto 定义文件:Examples.protooption java_package = "org.apache.hadoop.hbase. ...

  9. 进击的docker 一 : Docker 简介

    Docker简介 1.什么是docker 1.1.docker 起源 开源项目 诞生2013年初 GO语言开发实现 遵从了Apache2.0协议 项目代码在GitHub维护 1.2.docker目标 ...

  10. JS实现无缝滚动

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...