1 winform 讀取excel文檔
1)點擊button按鈕,彈出上傳excel窗口
private void button_headcompany_Click(object sender, EventArgs e)
{
string HeadCompany_rowValue = HeadCompany_row.Text;
string HeadCompany_columnValue = HeadCompany_column.Text;
if (string.IsNullOrEmpty(HeadCompany_rowValue) || string.IsNullOrEmpty(HeadCompany_columnValue))
{
MessageBox.Show("請填寫行和列的值,例如 行A5 列BB", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
ButtonClick("總公司匯總", HeadCompany_rowValue, HeadCompany_columnValue);
}
2)判斷是否上傳的文檔格式是否正常 xls和xlsx類型的文檔
public static void ButtonClick(string SheetType,string rowValue,string ColumnValue)
{
string worksheetname = string.Empty;
string filepath = "";
//導入本地文件
OpenFileDialog file = new OpenFileDialog();
file.Filter = "文檔(*.xls)|*.xls|文檔(*.xlsx)|*.xlsx";
if (file.ShowDialog() == DialogResult.OK) filepath = file.FileName;
string fileNameWithoutExtension = System.IO.Path.GetDirectoryName(filepath);// 沒有擴展名的文件名 “Default”
//判斷有沒有文件導入
if (file.FileName.Length == 0)
{
MessageBox.Show("請選擇要導入的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
DataSet ds = new DataSet();
DataTable dt = new DataTable();
////改變了原來的邏輯,直接從中間表導出數據Excel,ADDBYxingkai
// dt = Liveflow.HaiKang.ExcelHelper.ExcelToDataTable(filePath, 1, 27, -1, 0, 1);
//把excel表數據讀取到DataTable中
string strConn = string.Empty;
string excelName = SheetType;
//注意:把一個excel文件看做一個數據庫,一個sheet看做一張表。語法 "SELECT * FROM [sheet1$]",表單要使用"[]"和"$"
// 1、HDR表示要把第一行作為數據還是作為列名,作為數據用HDR=no,作為列名用HDR=yes;
// 2、通過IMEX=1來把混合型作為文本型讀取,避免null值。
// 3、判斷是xls還是xlsx
string[] sArray = filepath.Split('.');
if (sArray[1].ToString() == "xls")
{
// strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1';";
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"; // Office 07及以上版本 不能出現多余的空格 而且分號注意
//dt = HRManageXls(strConn, excelName, SheetType, fileNameWithoutExtension, rowValue, ColumnValue);
}
else if (sArray[1].ToString() == "xlsx")
{
strConn = "Provider=Microsoft.Ace.OleDb.12.0;data source='" + filepath + "';Extended Properties='Excel 12.0; HDR=NO; IMEX=1';";
HRManageXlsX(strConn, excelName, SheetType, fileNameWithoutExtension, rowValue, ColumnValue);
}
}
3)讀取excel文檔中的數據 轉換為datatable
public static void HRManageXlsX(string strConn, string excelName,string SheetType,string fileNameWithoutExtension, string rowValue, string ColumnValue)
{
DataTable dt = new DataTable();
dt=GetCsvToDataTable(strConn, excelName, SheetType,rowValue, ColumnValue);//獲取excel數據
//指定源列和目標列之間的對應關系
int row = dt.Rows.Count;//exce數據總行
int col = dt.Columns.Count;//excel數據總列
//生成兩張txt
for (int i = 0; i < row; i++)
{
if (i >= 2) {
if (!string.IsNullOrEmpty(dt.Rows[i][0].ToString()))
{
//總公司QuotaSQl.txt
string QuotaSQl = "INSERT INTO dbo.TB_HR_SatisfactionEvaluation_Quota(IId,EvaluationYear , EvaluationType , LocationName ,DescVal ,DeptName ,EvaluationDesc ,enable ,createby ,CreateTime ,updateby ,updateTime)VALUES (" + dt.Rows[i][4].ToString() + ",'2018', '" + dt.Rows[i][0].ToString() + "','" + dt.Rows[i][0].ToString() + "', '" + dt.Rows[i][2].ToString() + "','" + dt.Rows[i][1].ToString() + "','" + dt.Rows[i][3].ToString().Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "") + "', 1,'',GETDATE(),'' ,GETDATE());";
WriteLog(QuotaSQl, "總公司QuotaSQl", fileNameWithoutExtension);
}
if (!string.IsNullOrEmpty(dt.Rows[i][4].ToString()))
{
for (int j = 5; j < col; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
{
//總公司UserSQl.txt
string UserSQl = "INSERT INTO dbo.TB_HR_SatisfactionEvaluation_Quota_User( EvaluationYear ,QuotaID ,QuotoDept ,Quoter ,enable ,createby , CreateTime ,updateby ,updateTime ,Dept)VALUES ('2018','" + dt.Rows[i][4].ToString() + "','" + dt.Rows[0][j].ToString() + "','" + dt.Rows[i][j].ToString() + "',1,'sa',GETDATE(),'',GETDATE(),'');";
WriteLog(UserSQl, "總公司UserSQl", fileNameWithoutExtension);
}
}
}
}
}
MessageBox.Show("讀取信息完畢,已導出txt文件;路徑為"+ fileNameWithoutExtension + "", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
4)關鍵方法
public static DataTable GetCsvToDataTable(string strConn, string excelName, string FillName, string rowValue, string ColumnValue)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
System.Data.OleDb.OleDbDataAdapter odda = new System.Data.OleDb.OleDbDataAdapter(string.Format("select * from [" + excelName + "$"+ rowValue + ":"+ ColumnValue + "]"), conn); //這里的表名參數,就是 CSV的完整文件名
odda.Fill(ds, FillName);
conn.Close();
return ds.Tables[0];
}
5)寫入txt
/// <summary>
/// 寫入日志
/// </summary>
/// <param name="logstr">寫入的內容</param>
public static void WriteLog(string logstr,string Txtname,string fileNameWithoutExtension)
{
string strFileName = fileNameWithoutExtension+"/"+Txtname+ ".txt";
using (FileStream fs = new FileStream(strFileName, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
//聲明數據流文件寫入方法
sw.WriteLine(logstr);
sw.Close();
fs.Close();
}
}
}
