public void AddTask(string srcExcel, string destFile,ParseCompleteDelegate callBack ) { var task = new Tuple<string, string, ParseCompleteDelegate>(srcExcel, destFile, callBack); lock(_lock) { mTasks.Enqueue(task); } }
private bool ParseExcel(string srcRelativeExcel, string destRelativeFile, ParseCompleteDelegate callBack) { string srcExcel =Path.Combine(SrcRootPath, srcRelativeExcel); string destFile = Path.Combine(DestRootPath, destRelativeFile); FileStream stream = File.Open(srcExcel, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader = null; if (srcExcel.EndsWith(".xls")) { excelReader = ExcelReaderFactory.CreateBinaryReader(stream); } else if (srcExcel.EndsWith(".xlsx")) { excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } if (excelReader == null) return false; //DataSet - Create column names from first row //excelReader.IsFirstRowAsColumnNames = true; DataSet result = excelReader.AsDataSet(); if (result.Tables.Count < 1) return false; DataTable table = result.Tables[0]; int row = table.Rows.Count; int col = table.Columns.Count; if (row < 2 || col < 1) return false; List<string> header = new List<string>(); List<string> types = new List<string>(); StringBuilder txtContent = new StringBuilder(); for (int i = 0; i < row; i++) { if(i == 1) {//注释第二行的类型 txtContent.Append("#"); } for (int j = 0; j < col; j++) { if(j < col - 1) { txtContent.AppendFormat("{0}\t", table.Rows[i][j].ToString()); } else { txtContent.Append(table.Rows[i][j].ToString()); } if(i == 0) { header.Add(table.Rows[i][j].ToString()); } else if(i == 1) { types.Add(table.Rows[i][j].ToString()); } } txtContent.Append("\n"); } if(File.Exists(destFile)) { File.Delete(destFile); } FileStream output = File.OpenWrite(destFile); StreamWriter writer = new StreamWriter(output); writer.Write(txtContent.ToString()); writer.Flush(); writer.Close(); writer.Dispose(); output.Close(); output.Dispose(); //Free resources (IExcelDataReader is IDisposable) result.Dispose(); excelReader.Close(); excelReader.Dispose(); stream.Close(); stream.Dispose(); if(callBack != null) callBack(destRelativeFile, header, types); return true; }