Asp.net 导出Excel
//localizedHeaders 用来转换英文列到中文列
//trimUnlocalizedColumn 用来将隐藏的列,未本地化的列删除掉
==================================================================================================================
== Excel帮助类,调用NPOI组件
==================================================================================================================
public class ExcelHelper : IDisposable
{
private readonly string _fileName; //文件名
private IWorkbook _workbook;
private FileStream _fs;
private bool _disposed;
public ExcelHelper( string fileName)
{
_fileName = fileName;
_disposed = false;
}
/// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name=" data"> 要导入的数据 </param>
/// <param name=" isColumnWritten">DataTable的列名是否要导入 </param>
/// <param name=" sheetName"> 要导入的excel的sheet的名称 </param>
/// <returns> 导入数据行数(包含列名那一行) </returns>
public int DataTableToExcel( DataTable data, string sheetName, bool isColumnWritten)
{
int i;
int j;
int count;
ISheet sheet;
_fs = new FileStream(_fileName, FileMode .OpenOrCreate, FileAccess.ReadWrite);
if (_fileName.IndexOf( ".xlsx") > 0) // 2007版本
_workbook = new XSSFWorkbook();
else if (_fileName.IndexOf( ".xls") > 0) // 2003版本
_workbook = new HSSFWorkbook();
try
{
if (_workbook != null)
{
sheet = _workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
_workbook.Write(_fs); //写入到excel
return count;
}
catch ( Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return -1;
}
}
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name=" sheetName"> excel工作薄sheet的名称 </param>
/// <param name=" isFirstRowColumn">第一行是否是DataTable的列名 </param>
/// <returns> 返回的DataTable</returns>
public DataTable ExcelToDataTable( string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
_fs = new FileStream(_fileName, FileMode .Open, FileAccess .Read);
if (_fileName.IndexOf( ".xlsx") > 0) // 2007版本
_workbook = new XSSFWorkbook(_fs);
else if (_fileName.IndexOf( ".xls") > 0) // 2003版本
_workbook = new HSSFWorkbook(_fs);
if (sheetName != null)
{
sheet = _workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = _workbook.GetSheetAt(0);
}
}
else
{
sheet = _workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for ( int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.ToString();
DataColumn column = new DataColumn (cellValue);
data.Columns.Add(column);
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for ( int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for ( int j = row.FirstCellNum; j < cellCount; ++j)
{
ICell cell = row.GetCell(j);
if (cell.CellType == CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型
if ( DateUtil.IsCellDateFormatted(cell)) //日期类型
{
dataRow[j] = cell.DateCellValue;
}
else//其他数字类型
{
dataRow[j] = cell.NumericCellValue;
}
}
else if (cell.CellType == CellType.Blank) //空数据类型
{
dataRow[j] = "";
}
else if (cell.CellType == CellType.Formula) //公式类型
{
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(_workbook);
dataRow[j] = eva.Evaluate(cell).StringValue;
}
else //其他类型都按字符串类型来处理
{
dataRow[j] = cell.StringCellValue;
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch ( Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return null;
}
}
public void Dispose()
{
Dispose( true);
GC.SuppressFinalize( this);
}
protected virtual void Dispose( bool disposing)
{
if (! this._disposed)
{
if (disposing)
{
if (_fs != null)
_fs.Close();
}
_fs = null;
_disposed = true;
}
}
}
//trimUnlocalizedColumn 用来将隐藏的列,未本地化的列删除掉
public static class ResponseHelper
{
public static void ResponseExcel(string tempFolder,
DataTable dt,
Dictionary<string, LocalizedHeader> localizedHeaders,
bool trimUnlocalizedColumn,
string fileName,
string sheetName)
{
LocalizedColumnName(dt, localizedHeaders, trimUnlocalizedColumn);
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
if (string.IsNullOrEmpty(fileName))
{
fileName = Guid.NewGuid() + ".xls";
}
var excelPath = Path.Combine(tempFolder, fileName);
using (ExcelHelper helper = new ExcelHelper(excelPath))
{
helper.DataTableToExcel(dt, sheetName ?? "Sheet1", true);
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.WriteFile(excelPath);
HttpContext.Current.Response.End();
}
private static void LocalizedColumnName(DataTable dt, Dictionary<string, LocalizedHeader> localizedHeaders, bool trimUnlocalizedColumn)
{
if (localizedHeaders == null || localizedHeaders.Count == 0)
{
return;
}
var unlocalizedColumns = new List<string>();
foreach (DataColumn column in dt.Columns)
{
if (localizedHeaders.ContainsKey(column.ColumnName))
{
column.ColumnName = localizedHeaders[column.ColumnName].LocalizedName;
}
else
{
unlocalizedColumns.Add(column.ColumnName);
}
}
if (trimUnlocalizedColumn)
{
foreach (var unlocalizedColumn in unlocalizedColumns)
{
dt.Columns.Remove(dt.Columns[unlocalizedColumn]);
}
}
foreach (var localizedHeader in localizedHeaders)
{
if (dt.Columns.Contains(localizedHeader.Value.LocalizedName)
&& localizedHeader.Value.ColumnIndex < dt.Columns.Count)
{
{
dt.Columns[localizedHeader.Value.LocalizedName].SetOrdinal(localizedHeader.Value.ColumnIndex);
}
}
}
}
public class LocalizedHeader
{
public string OrignalName { get; set; }
public string LocalizedName { get; set; }
public int ColumnIndex { get; set; }
}
==================================================================================================================
== Excel帮助类,调用NPOI组件
==================================================================================================================
public class ExcelHelper : IDisposable
{
private readonly string _fileName; //文件名
private IWorkbook _workbook;
private FileStream _fs;
private bool _disposed;
public ExcelHelper( string fileName)
{
_fileName = fileName;
_disposed = false;
}
/// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name=" data"> 要导入的数据 </param>
/// <param name=" isColumnWritten">DataTable的列名是否要导入 </param>
/// <param name=" sheetName"> 要导入的excel的sheet的名称 </param>
/// <returns> 导入数据行数(包含列名那一行) </returns>
public int DataTableToExcel( DataTable data, string sheetName, bool isColumnWritten)
{
int i;
int j;
int count;
ISheet sheet;
_fs = new FileStream(_fileName, FileMode .OpenOrCreate, FileAccess.ReadWrite);
if (_fileName.IndexOf( ".xlsx") > 0) // 2007版本
_workbook = new XSSFWorkbook();
else if (_fileName.IndexOf( ".xls") > 0) // 2003版本
_workbook = new HSSFWorkbook();
try
{
if (_workbook != null)
{
sheet = _workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
_workbook.Write(_fs); //写入到excel
return count;
}
catch ( Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return -1;
}
}
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name=" sheetName"> excel工作薄sheet的名称 </param>
/// <param name=" isFirstRowColumn">第一行是否是DataTable的列名 </param>
/// <returns> 返回的DataTable</returns>
public DataTable ExcelToDataTable( string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
_fs = new FileStream(_fileName, FileMode .Open, FileAccess .Read);
if (_fileName.IndexOf( ".xlsx") > 0) // 2007版本
_workbook = new XSSFWorkbook(_fs);
else if (_fileName.IndexOf( ".xls") > 0) // 2003版本
_workbook = new HSSFWorkbook(_fs);
if (sheetName != null)
{
sheet = _workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = _workbook.GetSheetAt(0);
}
}
else
{
sheet = _workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for ( int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.ToString();
DataColumn column = new DataColumn (cellValue);
data.Columns.Add(column);
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for ( int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for ( int j = row.FirstCellNum; j < cellCount; ++j)
{
ICell cell = row.GetCell(j);
if (cell.CellType == CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型
if ( DateUtil.IsCellDateFormatted(cell)) //日期类型
{
dataRow[j] = cell.DateCellValue;
}
else//其他数字类型
{
dataRow[j] = cell.NumericCellValue;
}
}
else if (cell.CellType == CellType.Blank) //空数据类型
{
dataRow[j] = "";
}
else if (cell.CellType == CellType.Formula) //公式类型
{
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(_workbook);
dataRow[j] = eva.Evaluate(cell).StringValue;
}
else //其他类型都按字符串类型来处理
{
dataRow[j] = cell.StringCellValue;
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch ( Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return null;
}
}
public void Dispose()
{
Dispose( true);
GC.SuppressFinalize( this);
}
protected virtual void Dispose( bool disposing)
{
if (! this._disposed)
{
if (disposing)
{
if (_fs != null)
_fs.Close();
}
_fs = null;
_disposed = true;
}
}
}
作者:Jackhuclan
出处:http://jackhuclan.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://jackhuclan.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。