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();//表头行
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的更多相关文章
- NPOI操作Excel辅助类
/// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...
- NPOI操作excel之写入数据到excel表
在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...
- C#开发中使用Npoi操作excel实例代码
C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Exce ...
- 用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 ...
- C# 如何使用NPOI操作Excel以及读取合并单元格等
C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...
- 用NPOI操作EXCEL-锁定列CreateFreezePane()
public void ExportPermissionRoleData(string search, int roleStatus) { var workbook = new HSSFWorkboo ...
- .NET 通过 NPOI 操作 Excel
目录 .NET 通过 NPOI 操作 Excel 第一步:通过 NuGet 获取 NPOI 包并引入程序集 第二步:引入 NPOI 帮助类 第三步:在程序中调用相应的方法对数据进行导出导入操作 将 D ...
- 2.6.2 用NPOI操作EXCEL--设置密码才可以修改单元格内容
2.6.2 用NPOI操作EXCEL--设置密码 有时,我们可能需要某些单元格只读,如在做模板时,模板中的数据是不能随意让别人改的.在Excel中,可以通过“审阅->保护工作表”来完 ...
- 使用NPOI操作Excel文件及其日期处理
工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...
- C#通过NPOI操作Excel
参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...
随机推荐
- eworkflow工作流系统在iis中发布
eworkflow工作流系统在iis中发布 win7下面的iis发布eworkflow工作流系统,要带虚拟目录的,如发布成http://localhost/eworkflow/login.aspx这样 ...
- 删除Json中的不需要的键值
var json = {'A': 1, ,'B': 2, 'ccc': 333} delete json['ccc'];
- 使用Asp.net WebAPI 快速构建后台数据接口
现在的互联网应用,无论是web应用,还是移动APP,基本都需要实现非常多的数据访问接口.其实对一些轻应用来说Asp.net WebAPI是一个很快捷简单并且易于维护的后台数据接口框架.下面我们来快速构 ...
- javascript-with()方法
1)简要说明 with 语句可以方便地用来引用某个特定对象中已有的属性,但是不能用来给对象添加属性.要给对象创建新的属性,必须明确地引用该对象. 2)语法格式 with(object ...
- Spark Streaming源码解读之Driver中ReceiverTracker架构设计以具体实现彻底研究
本期内容 : ReceiverTracker的架构设计 消息循环系统 ReceiverTracker具体实现 一. ReceiverTracker的架构设计 1. ReceiverTracker可以以 ...
- 【Python】djangorestframework 基于django框架的接口开发
官网:http://www.django-rest-framework.org/#installation 下载:https://pypi.python.org/pypi/djangorestfram ...
- AC 设置DMZ口上网
- JVM调优
堆大小设置JVM 中最大堆大小有三方面限制:相关操作系统的数据模型(32-bt还是64-bit)限制;系统的可用虚拟内存限制;系统的可用物理内存限制.32位系统 下,一般限制在1.5G~2G;64为操 ...
- [HTML]JS全屏代码
video全屏参考:https://www.thecssninja.com/javascript/fullscreen <!doctype html> <html> <h ...
- java 在linux环境下写入 syslog 问题研究
1.Syslog 在Unix类操作系统上,syslog广泛应用于系统日志.syslog日志消息既可以记录在本地文件中,也可以通过网络发送到接收syslog的服务器.接收syslog的服务器可以对多个设 ...