using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace ChuPiao.Common.Utils
{
    public class ExcelUtil
    {
        private const int DEFAULT_COUNT = 1000;

        /// <summary>
        /// 导出excel，在调用后一定要调用  GC.Collect();//强行销毁Excel.exe进程，因为自己不能销毁自己，所以要在调用的进程中销毁
        /// </summary>
        /// <param name="dataGridView1"></param>
        /// <param name="saveFileName"></param>
        /// <returns></returns>
        public static string toExcel(DataGridView dataGridView1, string saveFileName)
        {
            return toExcel(dataGridView1,saveFileName,DEFAULT_COUNT);
        }


        public static string toExcel(DataGridView dataGridView1, string saveFileName,int interval)
        {
            if (interval <= 0 || interval > dataGridView1.RowCount)
            {
                if (dataGridView1.RowCount < DEFAULT_COUNT)
                    interval = dataGridView1.RowCount;
                else
                    interval = DEFAULT_COUNT;
            }
            try
            {
                int total = 0;
                int time = 0;
                //实例化一个Excel.Application对象 
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                if (excel == null)
                {
                    return "无法创建Excel对象，可能您的机子未安装Excel";
                }

                Microsoft.Office.Interop.Excel.Workbooks workbooks = excel.Workbooks;
                Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
                Microsoft.Office.Interop.Excel.Range range;
                //count是Excel中表头列的计数器，标识是表头的第几列
                int count = 1;
                //根据datagridview的列头确定工作表的表头
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    if (!(dataGridView1.Columns[i] is DataGridViewCheckBoxColumn))
                    {
                        worksheet.Cells[1, count] = dataGridView1.Columns[i].HeaderText;
                        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, count];
                        range.Interior.ColorIndex = 15;
                        range.Font.Bold = true;
                        //当此列不是CheckBox列时，计数器自增标识下一列
                        count++;
                    }
                }
                //此处count的值为daraGridView1中CheckBox的列数
                count = dataGridView1.Columns.Count - count + 1;
                //data数组存储的是dataGridView1中非CheckBox列的所有非文本数据
                object[,] data = new object[interval, dataGridView1.Columns.Count - count];
                total = dataGridView1.Rows.Count;
                time = (total + interval - 1) / interval;
                for (int t = 0; t < time; t++ )
                {
                    int start = t * interval;
                    int end = (t + 1) * interval;
                    if (t == time - 1)
                    {
                        end = dataGridView1.Rows.Count;
                    }
                    //col是data数组的列的索引
                    int col = 0;
                    for (int i = 0; i < dataGridView1.Columns.Count; i++)
                    {
                        if (!(dataGridView1.Columns[i] is DataGridViewCheckBoxColumn))
                        {
                            for (int r = start; r < end; r++)
                            {
                                data[r-start, col] = "'" + dataGridView1.Rows[r].Cells[i].Value;
                            }
                            //当该列不是CheckBox时自增
                            col++;
                        }
                    }
                    //startStr是本次Excel中的第一个单元格的标识例如"H8"
                    string startStr = "A" + (start+2);
                    //endStr是本次Excel中的最后一个单元格的标识例如"H8"

                    //解决列超过26列时的endStr的问题
                    int columnnum = dataGridView1.Columns.Count - count - 1;
                    string prestr = "";
                    for (int i = 0; i < columnnum / 26; i++)
                    {
                        prestr += "A";
                    }
                    string endStr = prestr + ((char)('A' + columnnum % 26)).ToString() + (end + 1);
                    range = worksheet.get_Range(startStr, endStr);
                    range.Value2 = data;

                    //自动调整列宽
                    worksheet.Columns.AutoFit();
                    
                    if (saveFileName != "")
                    {
                        try
                        {
                            workbook.Saved = true;
                            workbook.SaveCopyAs(saveFileName);
                        }
                        catch (Exception ex)
                        {
                            return "导出文件时出错,文件可能正被打开";
                        }
                    }
                    else
                    {
                        return "";
                    }

                }
                excel.Workbooks.Close();
                excel.Quit();
                
               // KillSpecialExcel(excel);
                return "导出文件成功";
            }
            catch (Exception ex)
            {
                return "导出异常\r\n错误提示:" + ex.Message;
            }

        }
    }
}
