簡體   English   中英

如何使用C#創建和寫入Excel .xls文件

[英]How to create and write Excel .xls file using C#

我很少運行3次測試,並且可以通過c#代碼計算平均值。如果以前以以下圖片格式創建的話,我可以將3次測試時間和平均值計算到xls文件中 xls文件格式 但是現在我必須每天使用Windows Scheduler通過批處理文件每小時運行每個測試。 我想以以下提到的格式每小時以特定的名稱動態創建一個xls文件,以便在第一次迭代時創建該文件,並在接下來的19次迭代中將其寫入同一文件,然后在下一個小時使用特定的名稱創建新文件名稱。如何動態創建和寫入Excel文件????? 如果還有其他簡單的程序,請建議。 我用來在已創建的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;

    }

   }
 }

`

有一種使用數據網格處理此問題的方法。

下面的示例接受一個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 { }
}

老實說,使用csv文件可能會更好,從ranorex測試中,您可以簡單地使用system.IO.File將輸出文本寫入文件,然后csv格式的好處是在excel中打開

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM