C# 創建Excel並寫入內容


 

  1.         1 增加應用      Microsoft.Office.Interop.Excel
  2.  
            2 引用命名空間  using Excel = Microsoft.Office.Interop.Excel;
  3.  
            /// <summary>
  4.  
    /// If the supplied excel File does not exist then Create it
  5.  
    /// </summary>
  6.  
    /// <param name="FileName"></param>
  7.  
    private void CreateExcelFile(string FileName)
  8.  
    {
  9.  
    //create
  10.  
    object Nothing = System.Reflection.Missing.Value;
  11.  
    var app = new Excel.Application();
  12.  
    app.Visible = false;
  13.  
    Excel.Workbook workBook = app.Workbooks.Add(Nothing);
  14.  
    Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Sheets[ 1];
  15.  
    worksheet.Name = "Work";
  16.  
    //headline
  17.  
    worksheet.Cells[ 1, 1] = "FileName";
  18.  
    worksheet.Cells[ 1, 2] = "FindString";
  19.  
    worksheet.Cells[ 1, 3] = "ReplaceString";
  20.  
     
  21.  
    worksheet.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
  22.  
    workBook.Close( false, Type.Missing, Type.Missing);
  23.  
    app.Quit();
  24.  
    }
  25.  
     
  26.  
    /// <summary>
  27.  
    /// open an excel file,then write the content to file
  28.  
    /// </summary>
  29.  
    /// <param name="FileName">file name</param>
  30.  
    /// <param name="findString">first cloumn</param>
  31.  
    /// <param name="replaceString">second cloumn</param>
  32.  
    private void WriteToExcel(string excelName,string filename,string findString,string replaceString)
  33.  
    {
  34.  
    //open
  35.  
    object Nothing = System.Reflection.Missing.Value;
  36.  
    var app = new Excel.Application();
  37.  
    app.Visible = false;
  38.  
    Excel.Workbook mybook = app.Workbooks.Open(excelName, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
  39.  
    Excel.Worksheet mysheet = (Excel.Worksheet)mybook.Worksheets[ 1];
  40.  
    mysheet.Activate();
  41.  
    //get activate sheet max row count
  42.  
    int maxrow = mysheet.UsedRange.Rows.Count + 1;
  43.  
    mysheet.Cells[maxrow, 1] = filename;
  44.  
    mysheet.Cells[maxrow, 2] = findString;
  45.  
    mysheet.Cells[maxrow, 3] = replaceString;
  46.  
    mybook.Save();
  47.  
    mybook.Close( false, Type.Missing, Type.Missing);
  48.  
    mybook = null;
  49.  
    //quit excel app
  50.  
    app.Quit();
  51.  
    }

 

轉載於:https://www.cnblogs.com/james1207/p/3278529.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM