//調(diào)用getExcelOneCell函數(shù)的整個(gè)過(guò)程,刪掉了源代碼中的實(shí)際需求部分,只保留調(diào)用和使用過(guò)程
using Microsoft.Office.Interop.Excel;
//界面接受選擇的excel文件
public ActionResult InputProFundSummary()
? ? ? ? {
? ? ? ? ? ? HttpPostedFileBase file = Request.Files["file"];//接收客戶端傳遞過(guò)來(lái)的數(shù)據(jù).
? ? ? ? ? ? if (String.IsNullOrEmpty(file.FileName))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return RedirectToAction("InputData", new { status = "請(qǐng)您選擇導(dǎo)入Excel文件" });
? ? ? ? ? ? }
? ? ? ? ? ? string SaveFilePath = Server.MapPath("~/TempFiles/") + file.FileName;
? ? ? ? ? ? file.SaveAs(SaveFilePath);
? ? ? ? ? ? string ret = "";
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? ret = InputProfundData(SaveFilePath, file.FileName);
? ? ? ? ? ? ? ? //----------上傳臨時(shí)文件---------
? ? ? ? ? ? ? ? UtiHelper.DeleteFile(SaveFilePath);
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return RedirectToAction("InputData", new { status = "導(dǎo)入失敗:" + ex.Message });
? ? ? ? ? ? }
? ? ? ? ? ? return RedirectToAction("InputData", new { status = ret == "true" ? "導(dǎo)入成功" : "導(dǎo)入失敗" });
? ? ? ? }
private string InputProfundData(string fileName, string prono)
? ? ? ? {
? ? ? ? ? ? var targetFile = new FileInfo(fileName);
? ? ? ? ? ? string strfile = targetFile.ToString();
? ? ? ? ? ? string? contents= ExcelHelp.getExcelOneCell(strfile, 2, 5);//獲取第2行第5列的內(nèi)容
? ? ? ? ? ? return contents;
? ? ? ? }
//獲取excel中某一行某一列的內(nèi)容
public string getExcelOneCell(string fileName, int row, int column)
? ? ? ? {
? ? ? ? ? ? Microsoft.Office.Interop.Excel.Application app = new Application();
? ? ? ? ? ? Workbook wbook = app.Workbooks.Open(fileName, Type.Missing, Type.Missing,
? ? ? ? ? ? ? Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
? ? ? ? ? ? ? Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
? ? ? ? ? ? ? Type.Missing, Type.Missing);
? ? ? ? ? ? Worksheet workSheet = (Worksheet)wbook.Worksheets[1];
? ? ? ? ? ? string temp = ((Range)workSheet.Cells[row, column]).Text.ToString();
? ? ? ? ? ? wbook.Close(false, fileName, false);
? ? ? ? ? ? app.Quit();
? ? ? ? ? ? NAR(app);
? ? ? ? ? ? NAR(wbook);
? ? ? ? ? ? NAR(workSheet);
? ? ? ? ? ? return temp;
? ? ? ? }
? ? ? ? //此函數(shù)用來(lái)釋放對(duì)象的相關(guān)資源
? ? ? ? private void NAR(Object o)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //使用此方法,來(lái)釋放引用某些資源的基礎(chǔ) COM對(duì)象。 這里的o就是要釋放的對(duì)象
? ? ? ? ? ? ? ? System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
? ? ? ? ? ? }
? ? ? ? ? ? catch { }
? ? ? ? ? ? finally
? ? ? ? ? ? {
? ? ? ? ? ? ? ? o = null; GC.Collect();
? ? ? ? ? ? }
? ? ? ? }