简体   繁体   English

将数据保存到Excel C#

[英]Save data to Excel C#

I've a code that read data from excel using Interop.Excel. 我有一个代码,可以使用Interop.Excel从excel读取数据。 The problem is when the second time I'm calling the write method it seems like it's being saved in another copy and just the first call actually write data to the original excel file. 问题是,当我第二次调用write方法时,似乎将其保存在另一个副本中,而只是第一次调用实际上将数据写入了原始excel文件。 It looks like the interop object won't clean up properly. 看来互操作对象无法正确清理。

This is the Read/Write methods 这是读/写方法

public class ExcelHelper
{
    Microsoft.Office.Interop.Excel.Application excelApp;
    static AppSettingsReader settingsReader = new AppSettingsReader();


    public string[,] getExcelInfo(string excelFileName)
    {

        string[,] dataArray;

        string logfileName = settingsReader.GetValue("LogFileName", typeof(string)).ToString();
        string logDirectory = settingsReader.GetValue("LogDirectory", typeof(string)).ToString();
        string logLevel = settingsReader.GetValue("LogLevel", typeof(string)).ToString();

        Logger.Log(logfileName, logDirectory, logLevel, "Getting File " + excelFileName);

        Workbook wb = excelApp.Workbooks.Open(excelFileName,null,true);
        Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = (Microsoft.Office.Interop.Excel._Worksheet)wb.Sheets[1];

        Worksheet ws = wb.Worksheets[1];

        Range range = ws.UsedRange;

       dataArray = new string[range.Rows.Count, range.Columns.Count];

        string str = string.Empty;
        int rCnt = 0;
        int cCnt = 0;

        for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
        {
            for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
            {



                dataArray[rCnt - 1, cCnt - 1] = System.Convert.ToString((range.Cells[rCnt, cCnt] as Range).Value2);




            }
        }

        wb.Close();


        releaseObject(range);
        releaseObject(ws);
        releaseObject(wb);



       return dataArray;


    }


    public static int WritePRSIdToExcel(int PRSInt, int line)
    {


      string excelApp = ConfigurationManager.AppSettings["excelFileName"];


      //  Application excel = (Application)Marshal.GetActiveObject("Excel.Application");
        _Application docExcel = (Application)Marshal.GetActiveObject("Excel.Application");
        docExcel.Visible = false;
        docExcel.DisplayAlerts = false;

        _Workbook workbooksExcel = docExcel.Workbooks.Open(excelApp, null, true);
        _Worksheet worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;


        Range range = worksheetExcel.UsedRange;


        string str;

        str = (string)(range.Cells[line, 3] as Microsoft.Office.Interop.Excel.Range).Value2;



        if (!(str == null))
        {

            ((Range)worksheetExcel.Cells[line + 1, 5]).Value2 = PRSInt;

            workbooksExcel.Save();
            GC.Collect();   
            GC.WaitForPendingFinalizers();
            workbooksExcel.Close(false, Type.Missing, Type.Missing);
            docExcel.Quit();
            docExcel.Application.DisplayAlerts = true;
            Marshal.ReleaseComObject(workbooksExcel);
            Marshal.ReleaseComObject(docExcel);
            Marshal.ReleaseComObject(worksheetExcel);
            Marshal.ReleaseComObject(range);

        }



        return PRSInt;


    }

This is the method to read the data that was written to to the cell: 这是读取写入到单元中的数据的方法:

public class GetIDNumber
{
    static AppSettingsReader settingsReader = new AppSettingsReader();



    static void Main(string[] args)
    {
        ExcelHelper excelHelper = new ExcelHelper();



        /// <summary>
        /// Log settings
        /// </summary>
        string logfileName = settingsReader.GetValue("LogFileName", typeof(string)).ToString();
        string logDirectory = settingsReader.GetValue("LogDirectory", typeof(string)).ToString();
        string logLevel = settingsReader.GetValue("LogLevel", typeof(string)).ToString();

        string excelFileName = settingsReader.GetValue("ExcelFileName", typeof(string)).ToString();
        string TeamProjectName = settingsReader.GetValue("TeamProject", typeof(string)).ToString();

        excelHelper.InitExcel();

        tfsHelper.Connect();

        string[,] dataArray = excelHelper.getExcelInfo(excelFileName);



        //handle data


        const int START_ROW = 1;
        const int PRODUCT_REQUIRMENT_TITLE_COL = 2;
        const int REQ_DESC = 3;
        const int WORKITEM_ID_COL = 4;
        const int REQUIRMENT_ACV_ID_COL = 5;
        const int RISK_COL = 6;

        int TFSId = 0;     
        int PRSId = 0;



        while (line < dataArray.GetLength(0))
        {

            line++;



                  if (!string.IsNullOrEmpty(dataArray[line, REQ_DESC]))
                  {

                                    string TfsId = string.Empty;

                                     TfsId = ((dataArray[line, 4]));

                  } 

          }






enter code here

Have you stepped through debugging to make sure you're str is not equal to null on the second run? 您是否已逐步调试以确保第二次运行时str不等于null? If that's the case the workbook won't be saved and the process won't be ended. 如果是这种情况,则不会保存工作簿,并且该过程也不会结束。

You should probably do your Excel clean-up in a "finally" statement instead of in an "if". 您可能应该在“ finally”语句中而不是在“ if”中进行Excel清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM