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