C# 文件上傳下載(Excel導入,多線程下載)


 //打開Excel文件,轉換為DataTable
      DataTable dtExcel;
1     private void OpenFile() 2     { 3       OpenFileDialog dialog = new OpenFileDialog(); 4       dialog.Filter = "Microsoft Excel files(*.xls)|*.xls;*.xlsx"; //篩選打開文件類型 :圖片 *.jpg|*.jpg|*.bmp|*.bmp ;"音頻文|*.mp3;*.wma;*.aac;*.midi;*.wav" 等等 5       if (dialog.ShowDialog() == DialogResult.OK) 6       { 7         dialogFileName = dialog.FileName; 8         dtExcel = ExcelToDataTable(dialogFileName, "sheet1", true); 9       } 10     }
 1         /// <summary>
 2         /// Excel轉Datatable
 3         /// </summary>
 4         /// <param name="fileName">文件名含后綴名</param>
 5         /// <param name="sheetName">Excel文件,頁名稱</param>
 6         /// <param name="isFirstRowColumn">是否將第一列作為表頭</param>
 7         /// <returns></returns>
 8         private DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
 9         {
10             IWorkbook workbook = null;
11             FileStream fs = null;
12             ISheet sheet = null;
13             DataTable data = new DataTable();
14             int startRow = 0;
15             try
16             {
17                 fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
18                 if (fileName.IndexOf(".xlsx") > 0) // 2007版本
19                     workbook = new XSSFWorkbook(fs);
20                 else if (fileName.IndexOf(".xls") > 0) // 2003版本
21                     workbook = new HSSFWorkbook(fs);
22 
23                 if (sheetName != null)
24                 {
25                     sheet = workbook.GetSheet(sheetName);
26                     if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
27                     {
28                         sheet = workbook.GetSheetAt(0);
29                     }
30                 }
31                 else
32                 {
33                     sheet = workbook.GetSheetAt(0);
34                 }
35                 if (sheet != null)
36                 {
37                     IRow firstRow = sheet.GetRow(0);
38                     int cellCount = firstRow.LastCellNum; //一行最后一個cell的編號 即總的列數
39 
40                     if (isFirstRowColumn)
41                     {
42                         for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
43                         {
44                             ICell cell = firstRow.GetCell(i);
45                             if (cell != null)
46                             {
47                                 string cellValue = cell.StringCellValue;
48                                 if (cellValue != null)
49                                 {
50                                     DataColumn column = new DataColumn(cellValue);
51                                     data.Columns.Add(column);
52                                 }
53                             }
54                         }
55                         startRow = sheet.FirstRowNum + 1;
56                     }
57                     else
58                     {
59                         startRow = sheet.FirstRowNum;
60                     }
61 
62                     //最后一列的標號
63                     int rowCount = sheet.LastRowNum;
64                     for (int i = startRow; i <= rowCount; ++i)
65                     {
66                         IRow row = sheet.GetRow(i);
67                         if (row == null) continue; //沒有數據的行默認是null       
68 
69                         DataRow dataRow = data.NewRow();
70                         for (int j = row.FirstCellNum; j < cellCount; ++j)
71                         {
72                             if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null
73                                 dataRow[j] = row.GetCell(j).ToString();
74                         }
75                         data.Rows.Add(dataRow);
76                     }
77                 }
78 
79                 return data;
80             }
81             catch (Exception ex)
82             {
83                 MyMessageBox.Show(ex.Message);
84                 return null;
85             }
86         }    

文件下載:

     private void DownLoad()
        {
            if (impdefineBM != null)
            {
                FolderBrowserDialog path = new FolderBrowserDialog();
                path.ShowDialog();
                if (path != null && path.SelectedPath != "")
                {
                    string url = @"http://192.168.1.1/XX.xls";      //下載地址
                    string name = "FileName";              // 文件名稱
                    string savefilepath = path.SelectedPath + "\\" + name + url.Substring(url.LastIndexOf("."));   //注意:下載文件名的命名 ,可根據實際需求調整調用的文件創建方式
                    MultiDownload download = new MultiDownload(5, url, savefilepath);   //調用多線程下載
                    download.Start();
                }
            }
        }
 #region 多線程下載
        public class MultiDownload
        {
            #region 變量

            private int _threadNum;             //線程數量
            private long _fileSize;             //文件大小
            private string _fileUrl;            //文件地址
            private string _fileName;           //文件名
            private string _savePath;           //保存路徑
            private short _threadCompleteNum;   //線程完成數量
            private bool _isComplete;           //是否完成
            private volatile int _downloadSize; //當前下載大小(實時的)
            private Thread[] _thread;           //線程數組
            private List<string> _tempFiles = new List<string>();
            private object locker = new object();

            #endregion
            #region 屬性
            /// <summary>
            /// 文件名
            /// </summary>
            public string FileName
            {
                get
                {
                    return _fileName;
                }
                set
                {
                    _fileName = value;
                }
            }
            /// <summary>
            /// 文件大小
            /// </summary>
            public long FileSize
            {
                get
                {
                    return _fileSize;
                }
            }
            /// <summary>
            /// 當前下載大小(實時的)
            /// </summary>
            public int DownloadSize
            {
                get
                {
                    return _downloadSize;
                }
            }
            /// <summary>
            /// 是否完成
            /// </summary>
            public bool IsComplete
            {
                get
                {
                    return _isComplete;
                }
            }
            /// <summary>
            /// 線程數量
            /// </summary>
            public int ThreadNum
            {
                get
                {
                    return _threadNum;
                }
            }
            /// <summary>
            /// 保存路徑
            /// </summary>
            public string SavePath
            {
                get
                {
                    return _savePath;
                }
                set
                {
                    _savePath = value;
                }
            }

            #endregion

            /// <summary>
            /// 構造函數
            /// </summary>
            /// <param name="threahNum">線程數量</param>
            /// <param name="fileUrl">文件Url路徑</param>
            /// <param name="savePath">本地保存路徑</param>
            public MultiDownload(int threahNum, string fileUrl, string savePath)
            {
                this._threadNum = threahNum;
                this._thread = new Thread[threahNum];
                this._fileUrl = fileUrl;
                this._savePath = savePath;
            }

            public void Start()
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                _fileSize = response.ContentLength;
                int singelNum = (int)(_fileSize / _threadNum);      //平均分配
                int remainder = (int)(_fileSize % _threadNum);      //獲取剩余的
                request.Abort();
                response.Close();
                for (int i = 0; i < _threadNum; i++)
                {
                    List<int> range = new List<int>();
                    range.Add(i * singelNum);
                    if (remainder != 0 && (_threadNum - 1) == i)    //剩余的交給最后一個線程
                        range.Add(i * singelNum + singelNum + remainder - 1);
                    else
                        range.Add(i * singelNum + singelNum - 1);
                    //下載指定位置的數據
                    int[] ran = new int[] { range[0], range[1] };
                    _thread[i] = new Thread(new ParameterizedThreadStart(Download));
                    _thread[i].Name = System.IO.Path.GetFileNameWithoutExtension(_fileUrl) + "_{0}".Replace("{0}", Convert.ToString(i + 1));
                    _thread[i].Start(ran);
                }
                //MessageBox.Show("下載完成!");
            }

            private void Download(object obj)
            {
                Stream httpFileStream = null, localFileStram = null;
                try
                {
                    int[] ran = obj as int[];
                    string tmpFileBlock = System.IO.Path.GetTempPath() + Thread.CurrentThread.Name + ".tmp";
                    _tempFiles.Add(tmpFileBlock);
                    HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(_fileUrl);
                    httprequest.AddRange(ran[0], ran[1]);
                    HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse();
                    httpFileStream = httpresponse.GetResponseStream();
                    localFileStram = new FileStream(tmpFileBlock, FileMode.Create);
                    byte[] by = new byte[5000];
                    int getByteSize = httpFileStream.Read(by, 0, (int)by.Length); //Read方法將返回讀入by變量中的總字節數
                    while (getByteSize > 0)
                    {
                        Thread.Sleep(20);
                        lock (locker) _downloadSize += getByteSize;
                        localFileStram.Write(by, 0, getByteSize);
                        getByteSize = httpFileStream.Read(by, 0, (int)by.Length);
                    }
                    lock (locker) _threadCompleteNum++;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message.ToString());
                }
                finally
                {
                    if (httpFileStream != null) httpFileStream.Dispose();
                    if (localFileStram != null) localFileStram.Dispose();
                }
                if (_threadCompleteNum == _threadNum)
                {
                    Complete();
                    _isComplete = true;
                }

            }

            /// <summary>
            /// 下載完成后合並文件塊
            /// </summary>
            private void Complete()
            {
                Stream mergeFile = null;
                BinaryWriter AddWriter = null;
                try
                {
                    using (mergeFile = new FileStream(@_savePath, FileMode.Create)) //根據實際情況調整FileMode
                    {
                        AddWriter = new BinaryWriter(mergeFile);
                        foreach (string file in _tempFiles)
                        {
                            using (FileStream fs = new FileStream(file, FileMode.Open))
                            {
                                BinaryReader TempReader = new BinaryReader(fs);
                                AddWriter.Write(TempReader.ReadBytes((int)fs.Length));
                                TempReader.Close();
                            }
                            File.Delete(file);
                        }
                    }
                    MyMessageBox.Show("下載完成!");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    if (AddWriter != null)
                    {
                        AddWriter.Close();
                        AddWriter.Dispose();
                    }
                    if (mergeFile != null)
                    {
                        mergeFile.Close();
                        mergeFile.Dispose();
                    }
                }
            }
        }

        #endregion

 


免責聲明!

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



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