<转>Npoi导入导出Excel操作<载>
//Datatable导出Excel
private static void GridToExcelByNPOI(DataTable dt, string strExcelFileName)
{
try
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1"); ICellStyle HeadercellStyle = workbook.CreateCellStyle();
HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//字体
NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
headerfont.Boldweight = (short)FontBoldWeight.Bold;
HeadercellStyle.SetFont(headerfont); //用column name 作为列名
int icolIndex = ;
IRow headerRow = sheet.CreateRow();
foreach (DataColumn item in dt.Columns)
{
ICell cell = headerRow.CreateCell(icolIndex);
cell.SetCellValue(item.ColumnName);
cell.CellStyle = HeadercellStyle;
icolIndex++;
} ICellStyle cellStyle = workbook.CreateCellStyle(); //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
cellfont.Boldweight = (short)FontBoldWeight.Normal;
cellStyle.SetFont(cellfont); //建立内容行
int iRowIndex = ;
int iCellIndex = ;
foreach (DataRow Rowitem in dt.Rows)
{
IRow DataRow = sheet.CreateRow(iRowIndex);
foreach (DataColumn Colitem in dt.Columns)
{ ICell cell = DataRow.CreateCell(iCellIndex);
cell.SetCellValue(Rowitem[Colitem].ToString());
cell.CellStyle = cellStyle;
iCellIndex++;
}
iCellIndex = ;
iRowIndex++;
} //自适应列宽度
for (int i = ; i < icolIndex; i++)
{
sheet.AutoSizeColumn(i);
} //写Excel
FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);
workbook.Write(file);
file.Flush();
file.Close(); MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_successfully"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
ILog log = LogManager.GetLogger("Exception Log");
log.Error(ex.Message + Environment.NewLine + ex.StackTrace);
//记录AuditTrail
CCFS.Framework.BLL.AuditTrailBLL.LogAuditTrail(ex); MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_failed"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally { workbook = null; } }
*********************************
/// <summary>
/// Excel文件导成Datatable
/// </summary>
/// <param name="strFilePath">Excel文件目录地址</param>
/// <param name="strTableName">Datatable表名</param>
/// <param name="iSheetIndex">Excel sheet index</param>
/// <returns></returns>
public static DataTable XlSToDataTable(string strFilePath, string strTableName,int iSheetIndex)
{ string strExtName = Path.GetExtension(strFilePath); DataTable dt = new DataTable();
if (!string.IsNullOrEmpty(strTableName))
{
dt.TableName = strTableName;
} if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx"))
{
using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(iSheetIndex); //列头
foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)
{
dt.Columns.Add(item.ToString(),typeof(string));
} //写入内容
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
while(rows.MoveNext())
{
IRow row = (HSSFRow)rows.Current;
if (row.RowNum == sheet.FirstRowNum)
{
continue;
} DataRow dr = dt.NewRow();
foreach (ICell item in row.Cells)
{
switch (item.CellType)
{
case CellType.Boolean:
dr[item.ColumnIndex] = item.BooleanCellValue;
break;
case CellType.Error:
dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
break;
case CellType.Formula:
switch (item.CachedFormulaResultType)
{
case CellType.Boolean:
dr[item.ColumnIndex] = item.BooleanCellValue;
break;
case CellType.Error:
dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(item))
{
dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
}
else
{
dr[item.ColumnIndex] = item.NumericCellValue;
}
break;
case CellType.String:
string str = item.StringCellValue;
if (!string.IsNullOrEmpty(str))
{
dr[item.ColumnIndex] = str.ToString();
}
else
{
dr[item.ColumnIndex] = null;
}
break;
case CellType.Unknown:
case CellType.Blank:
default:
dr[item.ColumnIndex] = string.Empty;
break;
}
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(item))
{
dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
}
else
{
dr[item.ColumnIndex] = item.NumericCellValue;
}
break;
case CellType.String:
string strValue = item.StringCellValue;
if (string.IsNullOrEmpty(strValue))
{
dr[item.ColumnIndex] = strValue.ToString();
}
else
{
dr[item.ColumnIndex] = null;
}
break;
case CellType.Unknown:
case CellType.Blank:
default:
dr[item.ColumnIndex] = string.Empty;
break;
}
}
dt.Rows.Add(dr);
}
}
} return dt;
}
。。。
转载别人的;
自己做个记录;
以后万一再用到了呢···
下面是另外的一份···可能版本不同吧···
private void ExportExcel_NOPI(DataTable table_data)
{ Dictionary<string, string> enToZh = new Dictionary<string, string>();//dataTable中需要转换的值<需要将key即datatable中的值转换为中文值>
enToZh.Add("ID", "序号"); enToZh.Add("LOGINDAYS", "总天数"); table_data.Columns.RemoveAt();
table_data.Columns.RemoveAt();//先要移除不需要的列
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet1 = hssfworkbook.CreateSheet("Excel"); ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
ICellStyle stringStyle = hssfworkbook.CreateCellStyle();
stringStyle.VerticalAlignment = VerticalAlignment.Center; //取得列宽
int columnCount = table_data.Columns.Count;
int[] arrColWidth = new int[columnCount];
int width = ;
foreach (DataColumn column in table_data.Columns)
{
arrColWidth[column.Ordinal] = width;
} int rowIndex = ;
string temp_col1 = "";
int col1_s = ; foreach (DataRow row in table_data.Rows)
{ #region 新建表,填充列头,样式
if (rowIndex == || rowIndex == )
{
if (rowIndex != )
{
sheet1 = hssfworkbook.CreateSheet();
} #region 列头及样式 IRow headerRow = sheet1.CreateRow();
//240,255,255
ICellStyle headStyle = hssfworkbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
headStyle.VerticalAlignment = VerticalAlignment.Center; headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;//将标题颜色设置成灰色
headStyle.FillPattern = FillPattern.SolidForeground;//FillPattern 为单元格背景色的填充样式
IFont font = hssfworkbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font); foreach (DataColumn column in table_data.Columns)
{ string columName = column.ColumnName;
if (enToZh.ContainsKey(columName))
{
headerRow.CreateCell(column.Ordinal).SetCellValue(enToZh[columName]);
}
else
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
sheet1.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + ) * );//设置列宽 } #endregion rowIndex = ;
}
#endregion #region 填充内容 int j = ;
IRow dataRow = sheet1.CreateRow(rowIndex);
foreach (DataColumn column in table_data.Columns)
{
ICell newCell = dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.CellStyle = stringStyle;
if (j == )
{
newCell.SetCellValue(rowIndex);
}
else if (drValue == "" && j > )//如果是"1",将单元格颜色变色
{
ICellStyle tempStyle = hssfworkbook.CreateCellStyle();
tempStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index;
tempStyle.FillPattern = FillPattern.SolidForeground;
newCell.CellStyle = tempStyle;
}
else
{
newCell.SetCellValue(drValue);
}
break;
case "System.Int32"://字符串类型
newCell.SetCellValue(drValue);
newCell.CellStyle = stringStyle;
break;
case "System.Double":
if (drValue != "")
{
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
}
else
{
newCell.SetCellValue("");
}
newCell.CellStyle = cellStyle;
break;
} #region 单元格合并(这里只合并第一列) if (j == && temp_col1 != drValue)
{
if (temp_col1 != "")
{
sheet1.AddMergedRegion(new CellRangeAddress(col1_s, rowIndex - , , ));
}
temp_col1 = drValue;
col1_s = rowIndex;
} #endregion j++;
}
#endregion rowIndex++;
} //冻结窗口 锁定表头和第一列
sheet1.CreateFreezePane(, , , ); //输出 Context.Response.ContentType = "application/vnd.ms-excel";
Context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "Excel.xls"));
Context.Response.Clear(); MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
file.WriteTo(Context.Response.OutputStream);
Context.Response.End();
}
<转>Npoi导入导出Excel操作<载>的更多相关文章
- Npoi导入导出Excel操作
之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...
- NPOI导入导出Excel
.net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交 代码: 第一步. 在页面里面加入2个隐藏的iframe, 如下 ...
- .Net core NPOI导入导出Excel
最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...
- NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中
以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...
- Excel操作--使用NPOI导入导出Excel为DataTable
1.ExcelHelper封装 namespace NPOI操作Excel { public class ExcelHelper { /// <summary> /// DataTable ...
- .net mvc利用NPOI导入导出excel
1.导出Excel :首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...
- ASP.Net MVC利用NPOI导入导出Excel
因近期项目遇到所以记录一下: 首先导出Excel: 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// <s ...
- net mvc 利用NPOI导入导出excel
1.导出Excel : 首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...
- NPOI 导入导出excel 支持 03 07
因为微软的office成本太高了,所以开发项目的时候电脑上没安装office,而是安装了wps.但开发语言用的是C#,所以直接调用微软的office组件是很方便的,但一方面慢,一方面成本高,所以从网上 ...
随机推荐
- JSTL(JSP Standard Tag Library)读书笔记
分类 Preifx 范例 核心标签库--- ...
- 成都普华永道税务开发的offer
首先这是一个.net税务开发的offer,我是做开发的. 有没有人在成都普华永道的,最近收到普华永道的offer,如果有的话请联系我.想知道里面的情况.最想知道里面的加班情况,薪资还是有点诱惑的.毕竟 ...
- [转载]使用HttpWebRequest进行请求时发生错误:基础连接已关闭,发送时发生错误处理
转载,原文来自 http://blog.csdn.net/hawksoft/article/details/21776009 最近调试原来的微信模拟登陆时发生了“基础连接已关闭,发送时发生错误”的错误 ...
- 编写高质量代码改善C#程序的157个建议[用抛异常替代返回错误、不要在不恰当的场合下引发异常、重新引发异常时使用inner Exception]
前言 自从.NET出现后,关于CLR异常机制的讨论就几乎从未停止过.迄今为止,CLR异常机制让人关注最多的一点就是“效率”问题.其实,这里存在认识上的误区,因为正常控制流程下的代码运行并不会出现问题, ...
- 编写高质量代码改善C#程序的157个建议[IEnumerable<T>和IQueryable<T>、LINQ避免迭代、LINQ替代迭代]
前言 本文已更新至http://www.cnblogs.com/aehyok/p/3624579.html .本文主要学习记录以下内容: 建议29.区别LINQ查询中的IEnumerable<T ...
- 每天一个linux命令(18):find 命令概览
Linux 下find命令在目录结构中搜索文件,并执行指定的操作.Linux下find命令提供了相当多的查找条件,功能很强大.由于find具有强大的功能,所 以它的选项也很多,其中大部分选项都值得我们 ...
- Javascript继承机制的设计
写软工作业时各种蛋疼:主要在于Javascript没有“子类”“父类”“接口”的概念,只能使用prototype来实现,看了下面一篇文章,感觉写得很不错~ http://www.ruanyifeng. ...
- Java设计模式-抽象工厂模式(Abstract Factory )
工厂方法模式有一个问题就是,类的创建依赖工厂类,也就是说,如果想要拓展程序,必须对工厂类进行修改,这违背了闭包原则,所以,从设计角度考虑,有一定的问题,如何解决?就用到抽象工厂模式,创建多个工厂类,这 ...
- 使用FMDB事务批量更新数据库
今天比较闲看到大家在群里讨论关于数据库操作的问题,其中谈到了“事务”这个词,坦白讲虽然作为计算机专业的学生,在上学的时候确实知道存储过程.触发器.事务等等这些名词的概念,但是由于毕业后从事的不是服务器 ...
- TCP/IP详解 笔记一
概述: Tcp-ip让网络上的计算机进行通信,而不管计算机和操作系统是否一样. 分层结构: Tcp/ip协议族是多层协议的组合,而tcp和ip只是其中的两个协议而已. 一个通信举例: 注意图的右上方: ...