简体   繁体   English

如何使用C#在特定单元格的Excel文件中写入数据

[英]How to write data in an excel file at particular cell using c#

Below is the code I'm using I'm calling Driver method and passing the respective parameters row coloumn etc after executing the code runs successfully but nothing is written on excel file , is it possible to send directly the cell number like b5 etc if yes what modifications should I make: 下面是我正在使用的代码,我调用Driver方法并在执行代码成功运行后传递相应的参数,例如column等,但是在excel文件中未写入任何内容,是否可以直接发送像b5等这样的单元格号我应该做哪些修改:

namespace PEPI_Performance.Utility
{
/// <summary>
/// Description of ExcelWriter.
/// </summary>

public class ExcelWriter
{
    /// <summary>
    /// Constructs a new instance.
    /// </summary>
    public ExcelWriter()
    {
        // Do not delete - a parameterless constructor is required!
    }

    Microsoft.Office.Interop.Excel.Application exlApp;
    Microsoft.Office.Interop.Excel.Workbook exlWB;
    Microsoft.Office.Interop.Excel.Worksheet exlWS;
    object misvalue = System.Reflection.Missing.Value;


    public void Driver(int row , int col, string time, int runNumber){
        //GlobalLib.clsExcel objExcel = new GlobalLib.clsExcel();
        //  Report.Info(ApplicationName);
        string sDataFile = "Ranorex_Reports.xls";
        //ClsExcel objExcel = new ClsExcel();
        //ArrayList colTF = null;
        //  int rowCount = 0;
        string sFilePath = Path.GetFullPath(sDataFile);
        Report.Success(sFilePath);

        string sOldvalue = "Vopak_Automation\\bin\\Debug\\" + sDataFile;
         sFilePath=sFilePath.Replace(sOldvalue,"")+
        "PEPI_Performance\\ExecutionReport\\"+ sDataFile;
        fnOpenExcel(sFilePath,runNumber);

        //colTF = objExcel.fnGetTestFlow();
        writeExcel(row,col,time);
        fnCloseExcel();
    }



    //Open Excel file
    public int fnOpenExcel(string sPath
    [System.Runtime.InteropServices.OptionalAttribute,
    System.Runtime.InteropServices.DefaultParameterValueAttribute(0)]  // ERROR:
    Optional parameters aren't supported in C#
                           int iSheet){

        int functionReturnValue = 0;
        try {

            exlApp = new Microsoft.Office.Interop.Excel.Application();
            exlApp.Visible = true ;
            //exlWB = exlApp.Workbooks.Open(sPath);
            exlWB =
 exlApp.Workbooks.Open(sPath,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);
            exlWS =(Microsoft.Office.Interop.Excel.Worksheet)exlWB.Worksheets[iSheet];
            //((Microsoft.Office.Interop.Excel._Worksheet)exlWS).Activate();
            //((Microsoft.Office.Interop.Excel.Worksheet)exlWS).Cells() = 2;




            functionReturnValue = 0;
            Report.Info(functionReturnValue.ToString());
        }
        catch (Exception ex) {
            functionReturnValue = -1;
            Report.Error(ex.Message);
        }
        return functionReturnValue;
    }


    // Close the excel file and release objects.
    public int fnCloseExcel(){
        //exlWB.Close();

        try{
            exlApp.Quit();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(exlWS);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exlWB);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exlApp);

            GC.GetTotalMemory(false);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.GetTotalMemory(true);
        }catch(Exception ex){
            Report.Error(ex.Message);
        }
        Report.Info("closed");
        return 0;
    }

    public void writeExcel(int i, int j , string time){
        Excel.Range exlRange = null;
        exlRange = (Excel.Range)exlWS.UsedRange;
        //exlRange.Select();
        Report.Info("hi");
        //(Excel.Range)exlRange.Cells[i, j]).Value2 != null;
        //(Excel.Range)exlRange.Cells[i , j].
        ((Excel.Range)exlRange.Cells["B5",Type.Missing]).Formula = time;
            //((Excel.Range)exlRange.Cells[i, j]).Value2 = time;
    }

   }
   }

I know two ways to refer the cells 我知道两种引用单元格的方法

either you can use the row and cell with integer or by cell reference 您可以将行和单元格与整数一起使用,也可以通过单元格引用来使用

below is the example 下面是例子

By CELL reference 通过CELL参考

public void writeExcel(int i, int j , string time){
        Excel.Range exlRange = null;
        exlRange = (Excel.Range)exlWS.UsedRange;
        //exlRange.Select();
        Report.Info("hi");

       // ((Excel.Range)exlRange.Cells["B5",Type.Missing]).Formula = time;
       //((Excel.Range)exlRange.Cells[i, j]).Value2 = time;

        exlWS.Range["B5"].Formula = time;


    }

By row and cell as integer 按行和单元格为整数

public void writeExcel(int i, int j , string time){
        Excel.Range exlRange = null;
        exlRange = (Excel.Range)exlWS.UsedRange;
        //exlRange.Select();
        Report.Info("hi");

       // ((Excel.Range)exlRange.Cells["B5",Type.Missing]).Formula = time;
       //((Excel.Range)exlRange.Cells[i, j]).Value2 = time;

       ((Microsoft.Office.Interop.Excel.Range)exlRange.Cells[2, 2]).Formula = time;


    }

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

相关问题 如何使用c#从XML文件读取特定数据并将其写入到现有Excel工作表 - How to Read a particular Data from XML file and Write it to an Existing Excel Sheet using c# 如果特定单元格使用C#“ReadOnly”,如何使用DataReader在excel单元格中写入 - how to write in excel cells using DataReader if a particular cell is “ReadOnly” using C# C#,如何更新 Excel 文件中的特定 Cell - C#, how to update particular Cell in an Excel file 如何使用带有C#的Selenium WebDriver将数据写入Excel文件? - How to write data into an Excel file using Selenium WebDriver with C#? 如何使用C#将Excel中的单元格设置为特定日期格式? - How to set a cell in Excel to a particular date format using C#? 如何使用C#将颜色应用于Excel单元格数据(至特定字符)? - How to Apply color to Excel cell data(to particular characters) using c#? 如何使用c#中的excel数据阅读器获取特定单元格的内容? - How to get the contents a particular cell using excel data reader in c#? 当使用 C# 中的模板创建文件时,如何更新 excel 文件单元格数据? - How to update the excel file cell data, when the file is created using a template in C#? 使用C#将数据从Excel工作表写入文本文件 - Write the data from an Excel sheet to the text file using C# 如何在C#中的特定位置写入数据? - How to write data at a particular position in c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM