/// <summary>
/// Excel幫助類
/// </summary>
public class ExcelHelpers
{
/// <summary>
/// 將Excel以文件流轉換DataTable
/// </summary>
/// <param name="hasTitle">是否有表頭</param>
/// <param name="path">文件路徑</param>
/// <param name="tableindex">文件簿索引</param>
public static DataTable ExcelToDataTableFormPath(bool hasTitle = true, string path = "", int tableindex = 0)
{
//新建Workbook
Workbook workbook = new Workbook();
//將當前路徑下的文件內容讀取到workbook對象里面
workbook.LoadFromFile(path);
//得到第一個Sheet頁
Worksheet sheet = workbook.Worksheets[tableindex];
return SheetToDataTable(hasTitle, sheet);
}
/// <summary>
/// 將Excel以文件流轉換DataTable
/// </summary>
/// <param name="hasTitle">是否有表頭</param>
/// <param name="stream">文件流</param>
/// <param name="tableindex">文件簿索引</param>
public static DataTable ExcelToDataTableFormStream(bool hasTitle = true, Stream stream = null,int tableindex = 0)
{
//新建Workbook
Workbook workbook = new Workbook();
//將文件流內容讀取到workbook對象里面
workbook.LoadFromStream(stream);
//得到第一個Sheet頁
Worksheet sheet = workbook.Worksheets[tableindex];
return SheetToDataTable(hasTitle,sheet);
}
private static DataTable SheetToDataTable(bool hasTitle,Worksheet sheet)
{
int iRowCount = sheet.Rows.Length;
int iColCount = sheet.Columns.Length;
DataTable dt = new DataTable();
//生成列頭
for (int i = 0; i < iColCount; i++)
{
var name = "column" + i;
if (hasTitle)
{
var txt = sheet.Range[1, i + 1].Text;
if (!string.IsNullOrEmpty(txt)) name = txt;
}
while (dt.Columns.Contains(name)) name = name + "_1";//重復行名稱會報錯。
dt.Columns.Add(new DataColumn(name, typeof(string)));
}
//生成行數據
int rowIdx = hasTitle ? 2 : 1;
for (int iRow = rowIdx; iRow <= iRowCount; iRow++)
{
DataRow dr = dt.NewRow();
for (int iCol = 1; iCol <= iColCount; iCol++)
{
dr[iCol - 1] = sheet.Range[iRow, iCol].Text;
}
dt.Rows.Add(dr);
}
return dt;
}
}
[C#] 使用Spire.XLS 將excel轉DataTable
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。