Excel的读写示例

public static void ExportCommon(List<string[]> dataList,string excelPath,string[] itemName)
       {
           Application appli = new Application();
           string path = excelPath.Substring(0, excelPath.LastIndexOfAny(new char[] {'\\', '/'}));
           if (!Directory.Exists(path))
           {
               Directory.CreateDirectory(path);
           }
           if (File.Exists(excelPath))
           {
               File.Delete(excelPath);
            
           }
           Workbook wb = appli.Workbooks.Add(true);
           Worksheet ws = (Worksheet)wb.Sheets.Item[1];
           Range range = ws.UsedRange;
           try
           {
               for (int i = 0; i < itemName.Length; i++)
               {
                   range.Item[1, i + 1] = itemName[i];
               }
               for (int i = 0; i < dataList.Count; i++)
               {
                   for (int j = 0; j < dataList[i].Length; j++)
                   {
                       range.Item[i + 2, j + 1] = dataList[i][j];
                   }
               }
               wb.SaveAs(excelPath);
           }
           finally
           {
               wb.Close();
               appli.Quit();
               //进程回收 不加这句话每次都会产生很多进程不会被回收
               System.Runtime.InteropServices.Marshal.ReleaseComObject(appli);
           }
       }
       

猜你喜欢

转载自blog.csdn.net/zoysia1314/article/details/86237840