NPOI 빅 데이터 분할 기록 같은 Excel

8397 단어 Excel
실현 과정: 유도 해 야 할 데이터 베 이 스 는 양 이 많 고 한 번 에 꺼 내 는 압력 이 좀 크기 때문에 분할 해서 꺼 내 같은 엑셀 로 가 져 옵 니 다.엑셀 2003 판 의 최대 줄 수 는 65536 줄 이 고 엑셀 2007 에서 시 작 된 버 전의 최대 줄 수 는 1048576 줄 이기 때문에 NPOI 내 보 낼 때 엑셀 2007 을 선택 했다.
Form1.cs
 
/*

      :

using System.IO;

using System.Threading.Tasks;

using NPOI.HSSF.UserModel;

using NPOI.SS.UserModel;

using NPOI.XSSF.UserModel;

*/

      

public Form1()

{

    InitializeComponent();

    List<DictionaryEntry> list = new List<DictionaryEntry>(){

          new DictionaryEntry(1, "XA"),

          new DictionaryEntry(2, "XB")

    };

    cbType.BindComboBox(list);                    

}



private void CreateExcel(string fileName)

{

    if (File.Exists(fileName))

        File.Delete(fileName);



    IWorkbook workbook = new XSSFWorkbook();

    ISheet sheet = workbook.CreateSheet("Sheet1");

    FileStream sw = File.Create(fileName);

    workbook.Write(sw);

    sw.Close();                   

}





private void btnExport_Click(object sender, EventArgs e)

{            

    try

    {

        Task.Factory.StartNew(() =>

        {

            txtSql.SafeCall(() =>

            {

                txtSql.AppendText("    ...\r
"); }); BusinessType businessType = GetBusinessType(); string[] sqlWhereArray = Sql.SqlWhereArray; string[] DateRemarkArray = Sql.DateRemarkArray; string fileName = string.Format("{0}.xlsx", businessType.ToString()); CreateExcel(fileName); string sqlCount = Sql.GetRecordSql(businessType, ""); int recordCount = db.ExecuteScalar(sqlCount); int sqlIndex = 0; int rowIndex = 0; foreach (string sqlWhre in sqlWhereArray) { sqlIndex++; FileStream fs = File.Open(fileName, FileMode.Open); IWorkbook workbook = new XSSFWorkbook(fs); ISheet sheet = workbook.GetSheetAt(0); txtSql.SafeCall(() => { txtSql.AppendText(" " + sqlIndex.ToString() + ":" + DateRemarkArray[sqlIndex - 1]); }); string sql = Sql.GetDataSql(businessType, sqlWhre); DataTable dt = db.GetDataSet(sql).Tables[0]; int columnsCount = dt.Columns.Count; if (sqlIndex == 1) { IRow row0 = sheet.CreateRow(0); for (int m = 0; m < columnsCount; m++) { DataColumn dc = dt.Columns[m]; row0.CreateCell(m).SetCellValue(dc.ColumnName); } } for (int i = 0; i < dt.Rows.Count; i++) { rowIndex++; DataRow dr = dt.Rows[i]; IRow row = sheet.CreateRow(rowIndex); for (int j = 0; j < columnsCount; j++) { row.CreateCell(j).SetCellValue(dr[j].ToString()); } lblMsg.SafeCall(() => { if(i == (dt.Rows.Count - 1)) txtSql.AppendText(" :" + (i+1).ToString() + "\r
"); lblMsg.Text = string.Format(" {0} , {1} ", sqlIndex.ToString(), (i + 1).ToString()); double x = rowIndex * 1.0 / recordCount * 100; lblProgress.Text = string.Format(" :{0}, {1} , :{2} %", recordCount.ToString(), rowIndex.ToString(), x.ToString("#0.0")); }); } FileStream outFs = new FileStream(fileName, FileMode.Open); workbook.Write(outFs); outFs.Close(); } }).ContinueWith(TaskEnded); } catch (Exception ex) { MessageBox.Show(" , :" + ex.Message); } } private void TaskEnded(Task task) { txtSql.SafeCall(() => { lblMsg.Text = " !"; txtSql.AppendText(" !\r
"); }); }

 
Extensions.cs
 
public static class Extensions

{

    public static void SafeCall(this Control ctrl, Action callback)

    {

        if (ctrl.InvokeRequired)

            ctrl.Invoke(callback);

        else

            callback();

    }

    public static void BindComboBox(this ComboBox cb, List<DictionaryEntry> list)

    {

        cb.DisplayMember = "Value";

        cb.ValueMember = "Key";

        cb.DataSource = list;

    }

}

Sql.cs
 
 
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace DataExport

{

    public enum BusinessType

    {

        XA = 1,

        XB = 2

    }



    public class Sql

    {

        /// <summary>

        ///     sql where  

        /// </summary>

        public static string[] SqlWhereArray = { 

                                 "   1 ",

                                 "   2 ",

                                 "   3 "

                                 };

        

        /// <summary>

        /// sql where    

        /// </summary>

        public static string[] DateRemarkArray = {  

                            "20130101 20130331",

                            "20130401 20130630",

			    "20130701 ",

                             };



        /// <summary>

        ///   sql  

        /// </summary>

        /// <param name="type"></param>

        /// <param name="columns"></param>

        /// <param name="sqlWhere"></param>

        /// <returns></returns>

        private static string GetSql(BusinessType type, string columns, string sqlWhere)

        {

            string sql = "";

            switch (type)

            {

                case BusinessType.XA:

                    sql = string.Format(@"SELECT {0}  FROMM tb1 WHERE 1=1 {1} ", columns, sqlWhere);

                    break;

                case BusinessType.XB:

                    sql = string.Format(@"SELECT {0}  FROMM tb2 WHERE 1=1 {1} ", columns, sqlWhere);

                    break;

            }





            return sql;

        }



        /// <summary>

        ///       

        /// </summary>

        /// <param name="type"></param>

        /// <param name="sqlWhere"></param>

        /// <returns></returns>

        public static string GetRecordSql(BusinessType type, string sqlWhere)

        {

            string columns = "count(*)";

            return GetSql(type, columns, sqlWhere);

        }



        /// <summary>

        ///     

        /// </summary>

        /// <param name="type"></param>

        /// <param name="sqlWhere"></param>

        /// <returns></returns>

        public static string GetDataSql(BusinessType type, string sqlWhere)

        {

            string columns = "";

            switch (type)

            {

                case BusinessType.XA:

                                columns = @"

                                col1  1,

				col2  2,

                                col3  3

                                 ";

                    break;

                case BusinessType.XB:

                                columns = @"

                                col1  1,

				col2  2

                                 ";

                    break;

               

                    }

            return GetSql(type, columns, sqlWhere);

       }

    }

}


 

좋은 웹페이지 즐겨찾기