using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace liuzhouzhan20180115
{
class ExportToExcel
{
private const int OLDOFFICEVESION = -4143;
private const int NEWOFFICEVESION = 56;
public static void exportToExcel(ArrayList dataArray, string filePath)
{
//保存excel文件的格式
int FormatNum;
//excel版本号
string Version;
//启动应用
Excel.Application xlApp = new Excel.Application();
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Excel.Workbooks workbooks = xlApp.Workbooks;
//创建文件
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//创建sheet
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
//获取你使用的excel 的版本号
Version = xlApp.Version;
//使用Excel 97-2003
if (Convert.ToDouble(Version) < 12)
{
FormatNum = OLDOFFICEVESION;
}
//使用 excel 2007或更新
else
{
FormatNum = NEWOFFICEVESION;
}
//添加输出excel表格的表头信息信息
//注意这里的excel对应的单元格第一个位置为[1,1],而不是我们平时定义[0,0]
ArrayList head = (ArrayList)dataArray[0];
for (int i = 0; i<head.Count; i++)
{
worksheet.Cells[1, i + 1] = head[i].ToString();
}
//添加输出excel表格的内容信息
for (int rowIndex = 1; rowIndex<dataArray.Count; rowIndex++)
{
ArrayList rowArr = (ArrayList)dataArray[rowIndex];
for (int cellIndex = 0; cellIndex<rowArr.Count; cellIndex++)
{
worksheet.Cells[rowIndex + 1, cellIndex + 1] = rowArr[cellIndex].ToString();
}
}
//删除已存在的excel文件,否则会无法保存创建的excel文件
if (File.Exists(filePath))
{
try
{
File.Delete(filePath);
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}
//保存,这里必须指定FormatNum文件的格式,否则无法打开创建的excel文件
workbook.SaveAs(filePath, FormatNum);
//workbook.SaveAs(filePath);
workbook.Close();
//显示创建的excel文件
//xlApp.Visible = true;
xlApp.Quit();
}
}
}