/// <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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...