将数据保存到Excel C#

时间:2013-10-15 17:43:55

标签: c# excel excel-interop

我有一个使用Interop.Excel从excel读取数据的代码。 问题是当我第二次调用write方法时,似乎它被保存在另一个副本中,而第一次调用实际上是将数据写入原始excel文件。看起来互操作对象无法正常清理。

这是读/写方法

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;


    }

这是读取写入单元格的数据的方法:

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

1 个答案:

答案 0 :(得分:1)

您是否已逐步完成调试以确保第二次运行时str&str不等于null?如果是这样的话,工作簿将无法保存,并且流程不会结束。

你应该在&#34;最后&#34;中进行Excel清理。声明而不是&#34; if&#34;。