偶爾一次午飯時人事說加班加到8點多,純手工復制粘貼Excel的內容,公司大概150多人吧,每次發工資時都需要這樣手動處理,將一個Excel拆分成150多個Excel,再把裡面的內容粘過去,如此循環。於是,我寫了個小程序幫人事MM解決。
主要是用到了NPOI生成Excel,根據每條記錄創建一個Excel,並讀取員工姓名作為文件名,並設置Excel為只讀。
導入和拆分在狀態欄都會有相應提示
/// <summary> /// 讀取excel /// </summary> /// <param name="filepath"></param> /// <returns></returns> public DataSet ToDataTable(string filePath,string fileName) { string connStr = ""; string fileType = System.IO.Path.GetExtension(fileName); if (string.IsNullOrEmpty(fileType)) return null; if (fileType == ".xls") { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\""; } else { connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; } string sql_F = "Select * FROM [{0}]"; OleDbConnection conn = null; OleDbDataAdapter da = null; DataTable dtSheetName = null; DataSet ds = new DataSet(); try { // 初始化連接,並打開 conn = new OleDbConnection(connStr); conn.Open(); // 獲取數據源的表定義元數據 string SheetName = ""; dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); // 初始化適配器 da = new OleDbDataAdapter(); for (int i = 0; i < dtSheetName.Rows.Count; i++) { SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"]; if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$")) { continue; } da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn); DataSet dsItem = new DataSet(); da.Fill(dsItem, "MyTable"); ds.Tables.Add(dsItem.Tables[0].Copy()); } } catch (Exception ex) { } finally { // 關閉連接 if (conn.State == ConnectionState.Open) { conn.Close(); da.Dispose(); conn.Dispose(); } } return ds; } public void ExcelSplit(DataTable excelTable) { //創建工作表 HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet1"); sheet.ProtectSheet("123"); //加密Excel,從而實現只讀 //創建表頭 IRow headerrow = sheet.CreateRow(0); for (int i = 0; i < excelTable.Columns.Count; i++) { headerrow.CreateCell(i).SetCellValue(excelTable.Columns[i].ColumnName); } int index = 0; //拆分個數 //創建內容 IRow datarow = sheet.CreateRow(1); FileStream stream = null; if (!Directory.Exists(@"d:/MyXls")) { Directory.CreateDirectory(@"d:/MyXls"); } for (int i = 0; i < excelTable.Rows.Count; i++) { for (int j = 0; j < excelTable.Columns.Count; j++) { ICell cell = datarow.CreateCell(j); cell.SetCellValue(excelTable.Rows[i][j].ToString()); } string excelname = excelTable.Rows[i]["姓名"].ToString()+"_"+DateTime.Now.ToString("yyyy-MM")+ ".xls"; stream = new FileStream(@"d:/MyXls/" + excelname, FileMode.Create); workbook.Write(stream); index++; } stream.Close(); this.toolStripStatusLabel1.Text = "共拆分工資條:" + index + "條"; this.Cursor = Cursors.Default; }
就是把它剪成一條條的
我們公司的工資條向來都由我們人事部剪的,工業園裡好幾家公司也都是由行政部剪的,不過別人向來都覺得我們做人事的都很閒,**地熊,我們忙得像頭熊的時候,她們怎麼沒看到