{ //數據導入 OpenFileDialog open = new OpenFileDialog(); open.Filter = "Excle文件|*.xls"; open.Title="導入數據...."; if (open.ShowDialog() != true) { return; } else { string filename = open.FileName; using (Stream stream = File.OpenRead(filename)) { HSSFWorkbook booke = new HSSFWorkbook(stream); ISheet sheet = booke.GetSheetAt(0); DataTable table = new DataTable(); table.Columns.Add("Name"); table.Columns.Add("Age"); table.Columns.Add("Indate"); // DataRow row = new DataRow(); // row["Name"]= for(int i=1;i< sheet.LastRowNum;i++) { IRow HssRow=sheet.GetRow(i); DataRow row = table.NewRow(); row["Name"] = HssRow.GetCell(0).StringCellValue; if (HssRow.GetCell(1).CellType == CellType.NUMERIC) { row["Age"] = HssRow.GetCell(1).NumericCellValue; } else if (HssRow.GetCell(1).CellType == CellType.STRING) { row["Age"] = Convert.ToInt32(HssRow.GetCell(1).NumericCellValue); } else { MessageBox.Show("數據類型出錯"); return; } if (HssRow.GetCell(2).CellType == CellType.NUMERIC) { row["Indate"] =(DateTime) HssRow.GetCell(2).DateCellValue;} table.Rows.Add(row); } TODB(table); } } } public void TODB(DataTable table) { using (SqlBulkCopy copy = new SqlBulkCopy("Password=HRMSys;Persist Security Info=True;User ID=HRMSys;Initial Catalog=HRMSys;Data Source=.")) { copy.DestinationTableName = "T_Tex"; copy.ColumnMappings.Add("Name","Name"); copy.ColumnMappings.Add("Age", "Age"); copy.ColumnMappings.Add("Indate", "Indate"); if (table == null) { MessageBox.Show("Table 參數爲空", "錯誤提示" ); return; } copy.WriteToServer(table); MessageBox.Show("數據導入成功","消息提示框"); refashush(); } }
//數據導出 SaveFileDialog save = new SaveFileDialog(); save.Filter="Excle文件|*.xls"; save.Title="保存文件...."; if (save.ShowDialog()!=true) { return; } else { List<TexMode> mo = this.listView.ItemsSource as List<TexMode>; TexMode [] mode= mo.ToArray(); if(mode==null) { MessageBox.Show("TexMode mode 數據爲空"); return; } string fileName =save.FileName; HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet= workbook.CreateSheet("員工數據"); IRow HeaderRow = sheet.CreateRow(0); HeaderRow.CreateCell(0, CellType.STRING).SetCellValue("姓名"); HeaderRow.CreateCell(1, CellType.NUMERIC).SetCellValue("年齡"); HeaderRow.CreateCell(2, CellType.STRING).SetCellValue("日期"); ICellStyle style = workbook.CreateCellStyle(); IDataFormat frommate = workbook.CreateDataFormat(); style.DataFormat = frommate.GetFormat("yyyy/m/d"); for (int i = 1;i< mode.Length; i++) { IRow row = sheet.CreateRow(i); row.CreateCell(0,CellType.STRING).SetCellValue(mode[i-1].Name); row.CreateCell(1, CellType.NUMERIC).SetCellValue(mode[i-1].Age); ICell indate = row.CreateCell(2,CellType.NUMERIC); indate.CellStyle = style; indate.SetCellValue(mode[i-1].Indate); } using (Stream strea = File.OpenWrite(fileName)) { workbook.Write(strea); } MessageBox.Show("文件保存在:" + fileName,"消息提示框"); }
<菜鳥學習大神勿噴> 測試代碼,提供的大概思路,部分代碼可精簡app