LinQtoExcel使用asp文件上传
本文关键字:文件 asp 使用 LinQtoExcel | 更新日期: 2023-09-27 18:26:22
im对此函数有问题。所以基本上用户会上传一个excel文件.xls(2003版本),然后点击导入按钮,它就会读取excel文件并将其导入sql数据库。
这是我的代码
protected void btnImport_Click(object sender, EventArgs e)
{
Business.Student student = new Business.Student();
int errorCount = 0;
int successCount = 0;
string successTotal;
int missinglastname = 0;
int missingfirstname = 0;
int missingmiddlename = 0;
if (filebiometrics.HasFile == false)
{
}
else
{
string pathToExcelFile = filebiometrics.FileName;
var excelFile = new ExcelQueryFactory(pathToExcelFile);
IEnumerable<string> worksheetnames = excelFile.GetWorksheetNames();
string worksheetName = excelFile.GetWorksheetNames().ToArray()[0];
var import = from a in excelFile.Worksheet<Business.Student.StudentList>(worksheetName) select a;
//var emptyfield = excelFile.Worksheet<Business.Employees.EmployeeImport>().Where(x => x.Surname != null).ToList();
excelFile.AddMapping<Business.Student.StudentList>(x => x.studentnumber, "Student Number");
excelFile.AddMapping<Business.Student.StudentList>(x => x.firstname, "Firstname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.lastname, "Lastname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.middlename, "Middlename");
string missing = "Missing!";
foreach (var a in import)
{
if (a.studentnumber == 0)
{
}
if (a.lastname == null)
{
a.lastname = missing;
missinglastname = missinglastname + 1;
}
if (a.firstname == "")
{
a.firstname = missing;
missingfirstname = missingfirstname + 1;
}
if (a.middlename == null)
{
missingmiddlename = missingmiddlename + 1;
}
else if (student.CheckExistingStudentNumber(a.studentnumber))
{
errorCount = errorCount + 1;
}
else
{
student.Create(a.studentnumber, a.firstname, a.lastname, a.middlename);
successCount = successCount + 1;
successTotal = "Total imported record: " + successCount.ToString();
}
}
txtLog.InnerText = "Total duplicate record: " + errorCount.ToString() +
Environment.NewLine +
"Total missing data on Firstname column: " + missingfirstname.ToString() +
Environment.NewLine +
"Total missing data on Lastname column: " + missinglastname.ToString() +
Environment.NewLine +
"Total missing data on middlename column: " + missingmiddlename.ToString() +
Environment.NewLine +
Environment.NewLine +
"Total imported record: " + successCount.ToString();
filebiometrics.Attributes.Clear();
}
}
我总是收到这个错误
错误在这一行"IEnumerable worksheetnames=excelFile.GetWorksheetNames();"
有人能帮我吗?
您的错误消息不言自明。错误在这一行:-
var excelFile = new ExcelQueryFactory(pathToExcelFile);
ExcelQueryFactory
需要完整的文件路径,但您只是使用string pathToExcelFile = filebiometrics.FileName;
传递excel文件名,显然它无法读取文件。
你需要读取用户正在上传的excel文件,并将其保存到服务器,然后像这样读取:-
string filename = Path.GetFileName(filebiometrics.FileName);
filebiometrics.SaveAs(Server.MapPath("~/") + filename);
var excelFile = new ExcelQueryFactory(Server.MapPath("~/") + filename);