具体实现代码:
private void button1_Click(object sender, EventArgs e)
{//导入
System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
string fileName = fd.FileName;
string[] s = fd.FileName.Split('\\');
textBox1.Text = s[s.Length - 1];
bind(fileName);
}
else
{
MessageBox.Show("文件不可为空,请选择需要导入的文件!");
}
}
DataTable dt = new DataTable();
DBOperate db = new DBOperate();
private void bind(string fileName)
{
//string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
// "Data Source=" + fileName + ";" +
// "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";此为老版本Excel读取方式
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + fileName + ";" +
"Extended Properties='Excel 12.0 Xml; HDR=Yes; IMEX=1'";//新版本Excel读取方式
string sql = " SELECT * FROM [sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(sql, strConn);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
dt = ds.Tables[0];
//this.dataGridView1.DataSource = dt;
this.ultraGrid1.DataSource = dt;
}
catch (Exception err)
{
MessageBox.Show("操作失败!" + err.ToString());
}
}
接下来将datatable中的数据保存到数据库中
private void button4_Click(object sender, EventArgs e)
{//保存到数据库
try
{
if (ultraGrid1.Rows.Count > 0)
{
bool b = false;
DataRow dr = null;
string text = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
if (text == null)
{
break;
}
else
{
b = insertToOra(dr, text);
if (b == false)
{
MessageBox.Show("导入失败,请检查数据是否合法!");
break;
}
}
}
if (b == true)
{ MessageBox.Show("导入成功!"); }
}
else
{
MessageBox.Show("数据为空!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private bool insertToOra(DataRow dr, string text)
{//导入到数据库执行函数
//excel表中的列名和数据库中的列名一定要对应
try
{
#region
string ariId = System.Guid.NewGuid().ToString("N");
string sample_id = dr[0].ToString();
string sql1 = "insert into T_PI_BH_ELEMENT values('" + ariId + "','" + sample_id + "')";
bool b1 = false;
DBOperate res = new DBOperate();
b1 = res.InsertData(sql1);
return b1 == true;
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
2.导出界面设计如下
通过查询条件来查询出相应的数据显示在UltraGrid上,然后导出UltraGrid上的数据
代码实现:
private void btnQuery_Click(object sender, EventArgs e)
{//查询
this.ugData.DataSource = GetDataFromOracle();
}
private DataTable GetDataFromOracle()
{//从数据库读取数据
string str = "";
if (!udteStart.DateTime.ToString().Equals("") || !udteEnd.DateTime.ToString().Equals(""))
{
str += " where SEL_TIME between to_date('" + udteStart.Value.ToString() + "','" + "YYYY-MM-DD HH24:MI:SS" + "') and to_date('"
+ udteEnd.Value.ToString() + "','" + "YYYY-MM-DD HH24:MI:SS" + "')";
}
if (!txtNo.Text.Equals(""))
{
str += " and SEQ_ID like '%" + txtNo.Text + "%'";
}
if (!textBox1.Text.Equals(""))
{
str += " and LS_ID like '%" + textBox1.Text + "%'";
}
if (!cmbGroup.Text.Equals(""))
{
str += " and CLASS_TYPE like '%" + cmbGroup.Text + "%'";
}
string sql = "select * from test" + str;
return db.GetQueryResult(sql);
}
导出
private void btnExport_Click(object sender, EventArgs e)
{//导出到Excel
ExportToExcel(ugData);
}
private void ExportToExcel(Infragistics.Win.UltraWinGrid.UltraGrid dgv)
{
//导出到execl
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "导出Excel (*.xlsx)|*.xlsx";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
if (strName.Length != 0)
{
//没有数据的话就不往下执行
if (dgv.DisplayLayout.Bands[0].Columns.Count == 0)
return;
// toolStripProgressBar1.Visible = true;
System.Reflection.Missing miss = System.Reflection.Missing.Value;
//实例化一个Excel.Application对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。
if (excel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
sheet.Name = "报告单";
int m = 0, n = 0;
//生成Excel中列头名称
for (int i = 0; i < dgv.DisplayLayout.Bands[0].Columns.Count; i++)
{
excel.Cells[1, i + 1] = dgv.DisplayLayout.Bands[0].Columns[i].Header.Caption;//输出UltraGrid列头名
}
//把UltraGrid当前页的数据保存在Excel中
for (int i = 0; i < dgv.Rows.Count - 1; i++)
{
for (int j = 0; j < dgv.DisplayLayout.Bands[0].Columns.Count; j++)
{
//excel.Cells[i + 2, j + 1] = dgv.Rows[i].Cells[j].Value.ToString();
if (j == 0)
{
if (dgv.Rows[i].Cells[j].Value.ToString().Length>8)
{
excel.Cells[i + 2, j + 1] = dgv.Rows[i].Cells[j].Value.ToString().Substring(8);
}
else if (dgv.Rows[i].Cells[j].Value.ToString().Equals(""))
{
excel.Cells[i + 2, j + 1] = "";
}
else
{
excel.Cells[i + 2, j + 1] = dgv.Rows[i].Cells[j].Value.ToString();
}
}
else
{
excel.Cells[i + 2, j + 1] = dgv.Rows[i].Cells[j].Value.ToString();
}
//excel.Cells[i + 2] = dgv.Rows[i].ToString();
//if (dgv.DisplayLayout.Bands[0].Columns[j]..ValueType == typeof(string))
//{
// excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();
//}
//else
//{
// excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();
//}
}
}
sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
book.Close(false, miss, miss);
books.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
GC.Collect();
MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
// toolStripProgressBar1.Value = 0;
System.Diagnostics.Process.Start(strName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误提示");
}
}