c#获取excel中某一单元格内容

//调用getExcelOneCell函数的整个过程,删掉了源代码中的实际需求部分,只保留调用和使用过程

using Microsoft.Office.Interop.Excel;

//界面接受选择的excel文件

public ActionResult InputProFundSummary()

        {

            HttpPostedFileBase file = Request.Files["file"];//接收客户端传递过来的数据.

            if (String.IsNullOrEmpty(file.FileName))

            {

                return RedirectToAction("InputData", new { status = "请您选择导入Excel文件" });

            }

            string SaveFilePath = Server.MapPath("~/TempFiles/") + file.FileName;

            file.SaveAs(SaveFilePath);

            string ret = "";

            try

            {

                ret = InputProfundData(SaveFilePath, file.FileName);

                //----------上传临时文件---------

                UtiHelper.DeleteFile(SaveFilePath);

            }

            catch (Exception ex)

            {

                return RedirectToAction("InputData", new { status = "导入失败:" + ex.Message });

            }

            return RedirectToAction("InputData", new { status = ret == "true" ? "导入成功" : "导入失败" });

        }

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列的内容

            return contents;

        }

//获取excel中某一行某一列的内容

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;

        }

        //此函数用来释放对象的相关资源

        private void NAR(Object o)

        {

            try

            {

                //使用此方法,来释放引用某些资源的基础 COM对象。 这里的o就是要释放的对象

                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);

            }

            catch { }

            finally

            {

                o = null; GC.Collect();

            }

        }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容