C#讀寫Excel


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Data;
using System.Data.OleDb;

namespace ExcelDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            OutLog("**************歡迎使用**************");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            //定義一個文件打開控件
            OpenFileDialog ofd = new OpenFileDialog();
            //設置打開對話框的初始目錄,默認目錄為exe運行文件所在的路徑
            //ofd.InitialDirectory = Application.StartupPath;
            //設置打開對話框的標題
            ofd.Title = "請選擇要打開的文件";
            //設置打開對話框可以多選
            ofd.Multiselect = true;
            //設置對話框打開的文件類型
            ofd.Filter = "excel03文件(*.xls)|*.xls|excel07文件(*.xlsx)|*.xlsx";
            //設置文件對話框當前選定的篩選器的索引
            ofd.FilterIndex = 2;
            //設置對話框是否記憶之前打開的目錄
            ofd.RestoreDirectory = true;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //獲取用戶選擇的文件完整路徑
                string[] filePath = ofd.FileNames;
                //獲取對話框中所選文件的文件名和擴展名,文件名不包括路徑
                string[] fileName = ofd.SafeFileNames;
                for (int i = 0; i < fileName.Length; i++)
                {
                    OutLog("用戶選擇的文件目錄為:" + filePath[i]);
                    OutLog("用戶選擇的文件名稱為:" + fileName[i]);
                    checkedListBox1.Items.Add(filePath[i], true);
                }

                //OutLog("**************選中文件的內容**************");
                //using (FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
                //{
                //    //定義二進制數組
                //    byte[] buffer = new byte[1024 * 1024 * 5];
                //    //從流中讀取字節
                //    int r = fsRead.Read(buffer, 0, buffer.Length);
                //    OutLog(Encoding.Default.GetString(buffer, 0, r));
                //}
            }

        }
        /// <summary>
        /// 輸出日志
        /// </summary>
        /// <param name="strLog"></param>
        private void OutLog(string strLog)
        {
            //如果日志信息長度超過1000行,則自動清空
            if (txt_FileInfo.GetLineFromCharIndex(txt_FileInfo.Text.Length) > 1000)
            {
                //清空文本
                txt_FileInfo.Clear();
            }
            txt_FileInfo.AppendText(DateTime.Now.ToString("HH:mm:ss ") + strLog + "\r\n");
        }

        private void linkLabel1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                checkedListBox1.SetItemCheckState(i, CheckState.Checked);
            }
        }

        private void linkLabel2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OutLog("准備中...");
            #region init
            string path = @"D:\" + DateTime.Now.Second + DateTime.Now.Millisecond + ".xlsx";
            System.Data.DataTable MyDataTable = new System.Data.DataTable();
            MyDataTable.Columns.Add(new DataColumn("存檔編號", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("任務描述", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("具體位置", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("開始時間", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("結束時間", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("工作情況", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("名稱1", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("型號1", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("數量1", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("名稱2", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("型號2", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("數量2", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("名稱3", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("型號3", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("數量3", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("名稱4", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("型號4", typeof(string)));
            MyDataTable.Columns.Add(new DataColumn("數量4", typeof(string)));
            #endregion
            DataRow dr;
            List<string[]> lstrs = new List<string[]>();
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                string[] str = new string[18];
                System.Data.DataTable dt = ExcelToDS(checkedListBox1.Items[i].ToString());
                //string IDCard =       dt.Rows[0][2].ToString();
                //string miaoshu =      dt.Rows[3][0].ToString();
                //string Position =     dt.Rows[4][0].ToString();
                //string StartTime =    dt.Rows[5][0].ToString();
                //string OverTime =     dt.Rows[5][2].ToString();
                //string Qingkuang =    dt.Rows[6][0].ToString();
                //string name_1 =       dt.Rows[8][0].ToString();
                //string Type_1 =       dt.Rows[8][1].ToString();
                //string Num_1 =        dt.Rows[8][4].ToString();
                //string name_2 =       dt.Rows[9][0].ToString();
                //string Type_2 =       dt.Rows[9][1].ToString();
                //string Num_2 =        dt.Rows[9][4].ToString();
                //string name_3 =       dt.Rows[10][0].ToString();
                //string Type_3 =       dt.Rows[10][1].ToString();
                //string Num_3 =        dt.Rows[10][4].ToString();
                //string name_4 =       dt.Rows[11][0].ToString();
                //string Type_4 =       dt.Rows[11][1].ToString();
                //string Num_4 =        dt.Rows[11][4].ToString();
                str[0] = dt.Rows[0][2].ToString().Split('')[1] + ".";
                str[1] = dt.Rows[3][0].ToString().Split('')[1];
                str[2] = dt.Rows[4][0].ToString().Split('')[1];
                str[3] = dt.Rows[5][0].ToString().Split('')[1];
                str[4] = dt.Rows[5][2].ToString().Split('')[1];
                str[5] = dt.Rows[6][0].ToString().Split('')[1];
                str[6] = dt.Rows[8][0].ToString().Split('')[1];
                str[7] = dt.Rows[8][1].ToString().Split('')[1];
                str[8] = dt.Rows[8][4].ToString().Split('')[1];
                str[9] = dt.Rows[9][0].ToString().Split('')[1];
                str[10] = dt.Rows[9][1].ToString().Split('')[1];
                str[11] = dt.Rows[9][4].ToString().Split('')[1];
                str[12] = dt.Rows[10][0].ToString().Split('')[1];
                str[13] = dt.Rows[10][1].ToString().Split('')[1];
                str[14] = dt.Rows[10][4].ToString().Split('')[1];
                str[15] = dt.Rows[11][0].ToString().Split('')[1];
                str[16] = dt.Rows[11][1].ToString().Split('')[1];
                str[17] = dt.Rows[11][4].ToString().Split('')[1];
                //DataRow dr = new System.Data.DataRow();
                //dr = MyDataTable.NewRow();
                //dr["存檔編號"] = IDCard;
                //dr["任務描述"] = miaoshu;
                //dr["具體位置"] = Position;
                //dr["開始時間"] = StartTime;
                //dr["結束時間"] = OverTime;
                //dr["工作情況"] = Qingkuang;
                //dr["名稱1"] = name_1;
                //dr["型號1"] = Type_1;
                //dr["數量1"] = Num_1;
                //dr["名稱2"] = name_2;
                //dr["型號2"] = Type_2;
                //dr["數量2"] = Num_2;
                //dr["名稱3"] = name_3;
                //dr["型號3"] = Type_3;
                //dr["數量3"] = Num_3;
                //dr["名稱4"] = name_4;
                //dr["型號4"] = Type_4;
                //dr["數量4"] = Num_4;
                //MyDataTable.Rows.Add(dr);
                lstrs.Add(str);
            }
            CreateExcelFile(path, lstrs);
            OutLog("准備完成!開始添加");
            DataSet ds = new System.Data.DataSet();
            ds.Tables.Add(MyDataTable);
            OutLog("OK,處理完成,文件路徑:" + path);
        }
        public System.Data.DataTable ExcelToDS(string Path)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select * from [sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");
            return ds.Tables[0];
        }
        public string CreateNewExcel()
        {
            string path = "D:/" + DateTime.Now.Second + DateTime.Now.Millisecond + ".xlsx";
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            OutLog("創建Excel文件,路徑:" + path);
            return path;
        }
        public void DSToExcel(string Path, DataSet oldds)
        {
            //先得到匯總EXCEL的DataSet 主要目的是獲得EXCEL在DataSet中的結構 
            string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + Path + ";Extended Properties=Excel 8.0";
            OleDbConnection myConn = new OleDbConnection(strCon);
            string strCom = "select * from [Sheet1$]";
            myConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            System.Data.OleDb.OleDbCommandBuilder builder = new OleDbCommandBuilder(myCommand);
            //QuotePrefix和QuoteSuffix主要是對builder生成InsertComment命令時使用。 
            builder.QuotePrefix = "[";     //獲取insert語句中保留字符(起始位置) 
            builder.QuoteSuffix = "]"; //獲取insert語句中保留字符(結束位置) 
            //DataSet newds = new DataSet();
            myCommand.Fill(oldds, "Table1");

            //for (int i = 0; i < oldds.Tables[0].Rows.Count; i++)
            //{
            //    //在這里不能使用ImportRow方法將一行導入到news中,因為ImportRow將保留原來DataRow的所有設置(DataRowState狀態不變)。在使用ImportRow后newds內有值,但不能更新到Excel中因為所有導入行的DataRowState!=Added 
            //    DataRow nrow = newds.Tables["Table1"].NewRow();
            //    for (int j = 0; j < newds.Tables[0].Columns.Count; j++)
            //    {
            //        nrow[j] = oldds.Tables[0].Rows[i][j];
            //    }
            //    newds.Tables["Table1"].Rows.Add(nrow);
            //}
            myCommand.Update(oldds, "Table1");
            myConn.Close();
        }
        public static void CreateExcelFile(string FileName, List<string[]> uu)
        {
            if (FileName.Split('.')[FileName.Split('.').Length - 1] == "xlsx")//如果是2007版以后
            {
                //create
                object Nothing = System.Reflection.Missing.Value;
                var app = new Microsoft.Office.Interop.Excel.Application();
                app.Visible = false;
                Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Add(Nothing);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[1];
                worksheet.Name = "Sheet1";
                //headline
                //int i = 1;
                //for (int i = 0; i < uu.Length; i++)
                //{
                //    worksheet.Cells[RowNum + 1, i + 1] = uu[i];
                //}
                worksheet.Cells[1, 1] = "存檔編號";
                worksheet.Cells[1, 2] = "任務描述";
                worksheet.Cells[1, 3] = "具體位置";
                worksheet.Cells[1, 4] = "開始時間";
                worksheet.Cells[1, 5] = "結束時間";
                worksheet.Cells[1, 6] = "工作情況";
                worksheet.Cells[1, 7] = "名稱1";
                worksheet.Cells[1, 8] = "型號1";
                worksheet.Cells[1, 9] = "數量1";
                worksheet.Cells[1, 10] = "名稱2";
                worksheet.Cells[1, 11] = "型號2";
                worksheet.Cells[1, 12] = "數量2";
                worksheet.Cells[1, 13] = "名稱3";
                worksheet.Cells[1, 14] = "型號3";
                worksheet.Cells[1, 15] = "數量3";
                worksheet.Cells[1, 16] = "名稱4";
                worksheet.Cells[1, 17] = "型號4";
                worksheet.Cells[1, 18] = "數量4";
                for (int i = 0; i < uu.Count; i++)
                {
                    for (int j = 0; j < uu[i].Length; j++)
                    {
                        worksheet.Cells[i + 2, j + 1] = uu[i][j];
                    }
                }
                //foreach (UUser uu in luu)
                //{

                //    worksheet.Cells[1, i] = uu.name;
                //    i++;
                //}


                worksheet.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
                workBook.Close(false, Type.Missing, Type.Missing);
                app.Quit();
            }
            //else
            //{
            //    HSSFWorkbook wk = new HSSFWorkbook();            //創建一個名稱為mySheet的表
            //    ISheet tb = wk.CreateSheet("Sheet1");
            //    //創建一行,此行為第二行
            //    IRow row = tb.CreateRow(1);
            //    for (int i = 0; i < luu.Count; i++)
            //    {
            //        ICell cell = row.CreateCell(i);  //在第二行中創建單元格
            //        cell.SetCellValue(luu[i].name);//循環往第二行的單元格中添加數據            }       
            //        using (FileStream fs = File.OpenWrite(FileName))
            //        {
            //            wk.Write(fs);   //向打開的這個xls文件中寫入mySheet表並保存。

            //        }
            //    }





            //}
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM