我正在做一个从 Excel 表读取数据并将其写入另一个 Excel 表的应用程序。我使用卷号作为我的搜索键值从源 Excel 表中检索值。
我的问题是,当存在单个卷号时,将检索值。我想检索多个卷号的数据。我怎么能做到这一点?我使用DataTable
来存储我检索到的值。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
namespace new1
{
public partial class Form1 : Form
{
static OleDbConnection oldb = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\sample.xlsx;Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\";");
OleDbCommand olc;
string fn;
OleDbDataAdapter adb = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
String cmd= "Select ";
int i = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
oldb = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\sample.xlsx;Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\";");
oldb.Open();
Excel.Application app = new Excel.Application();
app.Workbooks.Add();
Excel._Worksheet ws = app.ActiveSheet;
cmd += "* from [Sheet1$] where [Roll NUmber]="+textBox1.Text ;
olc = new OleDbCommand(cmd, oldb);
olc.ExecuteNonQuery();
adb.SelectCommand = olc;
adb.Fill(dt);
for (int i = 0; i < (dt.Rows.Count) - 1; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
ws.Cells[1, (j + 1)] = dt.Rows[i][j];
}
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "Excel Files|*.xlsx;*.xlsx";
sfd.Filter = "Excel Files|*.xlsx;*.xlsx";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
ws.SaveAs(sfd.FileName );
app.Quit();
}
catch (Exception ex)
{
MessageBox.Show("Problem" + ex.Message);
}
}
oldb.Close();
}