如何使用C#创建和编写Excel .xls文件

时间:2014-08-28 11:20:30

标签: c#

我有几次测试运行三次,平均值是通过c#代码计算出来的。我可以写三次测试时间,如果按照下面的图片格式xls file format创建,则平均到xls文件。但现在我必须每天通过使用Windows调度程序的批处理文件每小时运行一次测试。我想以下面提到的格式动态创建xls文件,并使用特定的名称,以便在第一次迭代时创建文件,然后在接下来的19次迭代中,它应该在同一个文件中写入,然后在下一个小时使用特定文件创建新文件name.How如何动态创建和编写excel文件????? 如果有任何其他简单的程序PLZ建议。我用来编写已经创建的xls文件的代码是:`/ *

using System;
using System.IO;
using Ranorex;

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!
    }


    public void Driver(int row , int col, string time, string sheetName){

        string sDataFile = "Ranorex_Reports.xls";
        string sFilePath = Path.GetFullPath(sDataFile);

        string sOldvalue = "Automation\\bin\\Debug\\" + sDataFile;
        sFilePath = sFilePath.Replace(sOldvalue,"")+
 "PEPI_Performance\\ExecutionReport\\" + sDataFile;
        fnOpenExcel(sFilePath,sheetName);
        writeExcel(row,col,time);
        fnCloseExcel();
    }
    Excel.Application   exlApp ;
    Excel.Workbook exlWB ;
    Excel.Sheets excelSheets ;
    Excel.Worksheet exlWS;
    //Open Excel file
    public int fnOpenExcel(string sPath, string iSheet){

        int functionReturnValue = 0;
        try {

            exlApp = new Excel.ApplicationClass(); 
            exlApp.Visible = true;
    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);

            // get all sheets in workbook
            excelSheets = exlWB.Worksheets;

            // get some sheet
            //string currentSheet = "Cycle1";
            exlWS = (Excel.Worksheet)excelSheets.get_Item(iSheet);
            functionReturnValue = 0;
        }
        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.ActiveWorkbook.Save();
            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);
        }
        return 0;
    }

    public void writeExcel(int i, int j , string time){
        Excel.Range exlRange = null;
        exlRange = (Excel.Range)exlWS.UsedRange;
        ((Excel.Range)exlRange.Cells[i,j]).Formula = time;

    }

   }
 }

`

2 个答案:

答案 0 :(得分:0)

有一种方法可以使用数据网格来处理这个问题。

下面的示例接受一个DataSet(您可以传递一个列表或表)。

然后在FLY上创建GridView并导出到Excel。我在很多网站上使用这种方法。

public static void ExportDataSetToExcel(DataSet ds, string filename)
{
    try
    {
        HttpResponse response = HttpContext.Current.Response;

        // first let's clean up the response.object
        response.Clear();
        response.Charset = "";

        // set the response mime type for excel
        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

        // create a string writer
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                // instantiate a datagrid
                DataGrid dg = new DataGrid();
                dg.DataSource = ds;
                dg.DataBind();
                dg.RenderControl(htw);
                response.Write(sw.ToString());
                response.End();
            }
        }
    }
    catch { }
}

答案 1 :(得分:0)

说实话,你可能最好使用csv文件,从你的ranorex测试中你可以简单地使用system.IO.File将输出文本写入文件,而csv格式的优点是它然后可以在excel中打开