第一次它正常工作,但第二次同样的文件上传它显示此错误:
The process cannot access the file 'D:....\UploadedFiles\FileName.xls' because it is being used by another process.
这是我的代码:
public ActionResult ImportExcel1()
{
try
{
string path1 = string.Format("{0}/{1}", Server.MapPath("~/UploadedFiles"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1)) {
System.IO.File.Delete(path1);
}
Request.Files["FileUpload1"].SaveAs(path1);
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path1);
Excel.Worksheet xlSheet = xlWorkbook.Sheets[1]; // get first sheet
Excel.Range xlRange = xlSheet.UsedRange; // get the entire used range
int numberOfRows = xlRange.Rows.Count;
int numberOfCols = xlRange.Columns.Count;
string slNo = "";
string batchCode = "";
string name = "";
string districtName = "";
string rollNo = "";
List<int> columnsToRead = new List<int>();
for (int i = 1; i <= numberOfCols; i++)
{
//if (xlRange.Cells[1, i].Value2 != null) // ADDED IN EDIT
//{
columnsToRead.Add(i);
//}
}
for (int j = 1; j <= numberOfRows; j++)
{
//if (xlRange.Cells[1, j].Value2 != null) // ADDED IN EDIT
//{
//if (xlRange.Cells[1, i].Value2.ToString().Equals("Currency Code"))
//{
// columnsToRead.Add(i);
//}
List<int> rowsToRead = new List<int>();
rowsToRead.Add(j);
foreach (int c in columnsToRead)
{
// start at 2 because the first row is 1 and the header row
foreach (int r in rowsToRead)
{
//if (xlRange.Cells[r, c].Value2 != null) // ADDED IN EDIT
//{
List<string> columnValue = new List<string>();
if (xlRange.Cells[r, c].Value2 == null) // ADDED IN EDIT
{
string x = "";
x = (xlRange.Cells[r, c].Value2) = "";
columnValue.Add(x);
}
else {
columnValue.Add(xlRange.Cells[r, c].Value2.ToString());
}
if (c.ToString() == "1") {
slNo = columnValue[0].ToString();
}
if (c.ToString() == "2") {
batchCode = columnValue[0].PadLeft(4, '0').ToString();
}
if (c.ToString() == "3") {
name = columnValue[0].ToString();
}
if (c.ToString() == "4") {
districtName = columnValue[0].ToString();
}
if (c.ToString() == "5") {
rollNo = columnValue[0].ToString();
}
}
if (j > numberOfRows) {
break;
}
}
SaveData(slNo, batchCode, name, districtName, rollNo);
}
xlApp.Workbooks.Close();
}
catch (Exception e) {
}
return RedirectToAction("Import");
}
答案 0 :(得分:0)
.xls文件未正确关闭。
xlWorkbook.Close(true, Type.Missing, Type.Missing); //Close() should have
//parameters based on your requirements.
xlApp.Workbooks.Close();
也可以使用finally块进行适当的清理。