2. 文件上载导入
/// <summary>
/// 上传Excel导入
/// </summary>
/// <param name="file">上载文件对象</param>
/// <param name="errorMsg">错误信息</param>
/// <param name="sheetName">表名,默认取第一张</param>
/// <returns></returns>
public static DataTable Import(System.Web.HttpPostedFileBase file, ref string errorMsg, string sheetName = "")
{
if (file == null || file.InputStream == null || file.InputStream.Length == 0)
{
errorMsg = "请选择要导入的Excel文件";
return null;
}
var excelType = GetExcelFileType(file.FileName);
if (excelType == null)
{
errorMsg = "请选择正确的Excel文件";
return null;
}
using (var stream = new MemoryStream())
{
file.InputStream.Position = 0;
file.InputStream.CopyTo(stream);
var dt = ImportExcel(stream, excelType.Value, sheetName);
if (dt == null)
errorMsg = "导入失败,请选择正确的Excel文件";
return dt;
}
}
3. 本地路径读取导入
/// <summary>
/// 根据文件路径导入Excel
/// </summary>
/// <param name="filePath"></param>
/// <param name="errorMsg">错误信息</param>
/// <param name="sheetName">表名,默认取第一张</param>
/// <returns>可能为null的DataTable</returns>
public static DataTable Import(string filePath, ref string errorMsg, string sheetName = "")
{
var excelType = GetExcelFileType(filePath);
if (GetExcelFileType(filePath) == null)
{
errorMsg = "请选择正确的Excel文件";
return null;
}
if (!File.Exists(filePath))
{
errorMsg = "没有找到要导入的Excel文件";
return null;
}
DataTable dt;
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
dt = ImportExcel(stream, excelType.Value, sheetName);
}
if (dt == null)
errorMsg = "导入失败,请选择正确的Excel文件";
return dt;
}
4.完整demo
附赠一个winform导入Excel的Demo。
https://github.com/yimogit/NopiExcelDemo
注:相关教程知识阅读请移步到c#教程频道。










