在Excel文件中附加值而不覆盖

时间:2019-04-18 07:14:20

标签: c# excel console-application

我正在使用C#开发控制台应用程序。我有一些需要处理的记录。使用循环,我正在读取值,将其添加到列表中,然后将其传递给函数。功能是将值写入Excel文件中。以下是我的代码

foreach (DataRow dr in dt.Rows)
{
 string uniqueID = dr["Application_No"].ToString();
 .
// other code
 .
 .
 string soapResult;
                        using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
                        {
                            using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
                            {
                                soapResult = rd.ReadToEnd();
                                var result = XmlDecode(soapResult);
                                XDocument doc = XDocument.Parse(result);

                                XmlReader read = doc.CreateReader();
                                DataSet ds = new DataSet();
                                ds.ReadXml(read);
                                read.Close();

                                if (ds.Tables.Count > 0 && ds.Tables["Reply"] != null && ds.Tables["Reply"].Rows.Count > 0)
                                {
                                    kwhRead1 = GetRead(ds, ReadTypeEnum.KWH1);
                                    kvhRead1 = GetRead(ds, ReadTypeEnum.KVH1);
                                    mdiRead1 = GetRead(ds, ReadTypeEnum.MDI1);

                                    kwhRead2 = GetRead(ds, ReadTypeEnum.KWH2);
                                    kvhRead2 = GetRead(ds, ReadTypeEnum.KVH2);
                                    mdiRead2 = GetRead(ds, ReadTypeEnum.MDI2);

                                    string ts = GetTSpan(ds, ReadTypeEnum.KWH1).Replace("T", " ");
                                    timeSpan = ts.Remove(ts.Length-6);


                                    if (ds.Tables["Reply"].Rows[0][0].ToString().ToUpper() == "OK")
                                    {

                                        if (ds.Tables["Names"] != null && ds.Tables["Names"].Rows.Count > 0)
                                        {
                                            uniqueKey = ds.Tables["Names"].Rows[0]["name"].ToString();
                                        }

                                        if (ds.Tables["NameType"] != null && ds.Tables["NameType"].Rows.Count > 0)
                                        {
                                            refNo = ds.Tables["NameType"].Rows[0]["name"].ToString();
                                        }

                                        if (ds.Tables["Meter"] != null && ds.Tables["Meter"].Rows.Count > 0)
                                        {
                                            if (ds.Tables["Meter"].Columns.Contains("mRID"))
                                            {
                                                meterNo = ds.Tables["Meter"].Rows[0]["mRID"].ToString();
                                                processedRec++;
                                            }
                                        }
                                    }                                                                          
                                     string completion_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                                    log = uniqueKey + " | " + refNo + " | " + meterNo + " | " + kwhRead1 + " | " + kwhRead2 + " | "
                                          + kvhRead1 + " | " + kvhRead2 + " | " + mdiRead1 + " | " + mdiRead2 + " | " + timeSpan + " | " + completion_time + " | ";

                                    ls.Add(log);
                                }
                                writeExcelFile(location,ls);



                            }

                        }

列表ls中有37010732575 | 28372830035610U | 002999001210 | 2.437 | 13.646 | 2.418 | 10.651 | 0.052 | 0.574 | 2019-03-01 00:00:00 | 2019-04-18 11:46:05 |

Excel功能

 public static void writeExcelFile(string location, List<string> ls)
    {          

        //Create excel app object
        Microsoft.Office.Interop.Excel.Application xlSamp = new Microsoft.Office.Interop.Excel.Application();
        if (xlSamp == null)
        {
            Console.WriteLine("Excel is not Insatalled");
            Console.ReadKey();
            return;
        }

        //Create a new excel book and sheet
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;


        xlWorkBook = xlSamp.Workbooks.Add(misValue);
        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        //Adding headers.
        xlWorkSheet.Cells[1, 1] = "Unique_ID"; //37010732575
        xlWorkSheet.Cells[1, 2] = "Ref_No"; // 28372830035610U
        xlWorkSheet.Cells[1, 3] = "Meter_No";//002999001210 
        xlWorkSheet.Cells[1, 4] = "kWh1";//2.437
        xlWorkSheet.Cells[1, 5] = "kWh2";//13.646
        xlWorkSheet.Cells[1, 6] = "kVarh1";//2.418
        xlWorkSheet.Cells[1, 7] = "kVarh2";//10.651
        xlWorkSheet.Cells[1, 8] = "MDI1";//0.052
        xlWorkSheet.Cells[1, 9] = "MDI2";//0.574
        xlWorkSheet.Cells[1, 10] = "Date_Time";//2019-03-01 00:00:00
        xlWorkSheet.Cells[1, 11] = "Completion_Time";//2019-04-18 11:46:05

        //Save the opened excel book to custom location
        //Dont forget, you have to add to exist location
        xlWorkBook.SaveAs(location, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
            Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlSamp.Quit();

        //release Excel Object 
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSamp);
            xlSamp = null;
        }
        catch (Exception ex)
        {
            xlSamp = null;
            Console.Write("Error " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }

    }
}

现在,我想将列表中的数据写入excel文件。当我使用foreach时,列表ls中的值将每次更改。所以我想以

的方式写入excel文件
  1. 每个值将保存在标题下
  2. 在第一行完成之后,下一个值应放在下一行。

我该怎么做?

任何帮助将不胜感激

0 个答案:

没有答案