StringBuilder str = new StringBuilder();
str.Append(DateTime.Now.Millisecond);
string url = "/Content/" + str + ".xlsx";
var path = Server.MapPath(url);
string data ;
int i = Models.ExcelHelper.DataTableToExcel(path,Models.Extensions.ToDataTable(a), "a", true);
public class ExcelHelper
{
#region NPOI方式
/// <summary>
/// 將excel中的數據導入到DataTable中
/// </summary>
/// <param name="fileName">excel的文件名(完整路徑)</param>
/// <param name="sheetName">excel工作薄sheet的名稱</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public static DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
{
IWorkbook workbook = null;
ISheet sheet = null;
FileStream fs = 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.StringCellValue;
if (cellValue != null)
{
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)
{
if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
/// <summary>
/// 將DataTable數據導入到excel中
/// </summary>
/// <param name="fileName">要導出的文件名</param>
/// <param name="data">要導出的數據</param>
/// <param name="sheetName">excel的sheet的名稱</param>
/// <param name="isColumnWritten">DataTable的列名是否要導入</param>
/// <returns>導入數據行數(包含列名那一行)</returns>
public static int DataTableToExcel(string fileName, DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
IWorkbook workbook = null;
FileStream fs = null;
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>
/// 將DataTable數據導入到excel中
/// </summary>
/// <param name="data">要導出的數據</param>
/// <param name="sheetName">excel的sheet的名稱</param>
/// <param name="isColumnWritten">DataTable的列名是否要導入</param>
/// <returns></returns>
public static byte[] DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
IWorkbook workbook = null;
MemoryStream fs = null;
fs = new MemoryStream();
workbook = new XSSFWorkbook();
try
{
if (workbook != null)
sheet = workbook.CreateSheet(sheetName);
else
return null;
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 fs.ToArray();
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
#endregion
#region 使用此方法時 運行機器上需要安裝Office組件
/// <summary>
/// 從指定的Excell文件中獲取數據,要求必須是規范的二維表數據且excel文件的首行為字段名
/// </summary>
/// <param name="fileUrl">服務器上的文件路徑</param>
/// <param name="head">獲取哪些字段的值(例如:編號,姓名,入學時間),不提供時返回所有列</param>
/// <returns>承載數據的DataSet</returns>
public static DataSet ImportDataFromExcell(string fileUrl, string head = "")
{
//string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileUrl + ";Extended Properties=Excel 8.0";//07之前版本使用
string connExcel = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + fileUrl + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; //此連接可以操作.xls與.xlsx文件 (支持Excel2003 和 Excel2007 的連接字符串)
using (OleDbConnection oleDbConnection = new OleDbConnection(connExcel))
{
oleDbConnection.Open();
//獲得Excel的每頁上的信息
DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//獲得Excel中的頁數
int pages = dataTable.Rows.Count;
string tableName = "";
string query = "";
DataSet ds = new DataSet();
OleDbDataAdapter oleAdapter = null;
for (int i = 0; i < pages; i++)
{
//獲得每一頁的名稱
tableName = dataTable.Rows[i][2].ToString().Trim();
string tn = tableName.Remove(tableName.Length - 1);
tableName = "[" + tableName.Replace("'", "") + "]";
if (string.IsNullOrEmpty(head))
query = "SELECT * FROM " + tableName;
else
query = "SELECT " + head + " FROM " + tableName;
oleAdapter = new OleDbDataAdapter(query, connExcel);
//表示每頁上的內容
DataTable dt = new DataTable(tn);
oleAdapter.Fill(dt);
ds.Tables.Add(dt);
}
return ds;
}
}
#endregion
}
/// <summary>
/// 擴展代碼之用
/// </summary>
public static class Extensions
{
#region 將集合對象轉為DataTable
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
public static DataTable ToDataTable<T>(this List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}
#endregion
}