private void toolStripButton4_Click(object sender, EventArgs e)
{
//打开一个文件选择框
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Excel文件";
ofd.FileName = "";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//为了获取特定的系统文件夹,可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举,其中可以定义要返回路径的哪个系统目录
ofd.Filter = "所有文件(*.*)|*.*|Excel2003文件(*.xls)|*.xls|Excel2007文件(*.xlsx)|*.xlsx"; //获取或设置筛选器字符串,该字符串确定在 SaveFileDialog 中显示的文件类型
ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
ofd.CheckFileExists = true; //验证路径有效性
ofd.CheckPathExists = true; //验证文件有效性
string strName = string.Empty;
if (ofd.ShowDialog() == DialogResult.OK)
{
strName = ofd.FileName;
} if (strName == "")
{
MessageBox.Show("没有选择Excel文件!无法进行数据导入");
return;
}
//调用导入数据方法
EcxelToDataGridView(strName, this.dataGridView1); }
/// <summary>
/// 导入Excel的方法
/// </summary>
/// <param name="filePath">Excel所存放的路径</param>
/// <param name="dgv">所要存放的DataGridView的名称</param>
/// <param name="excelName">Excel表中SHEET的名字</param>
public void EcxelToDataGridView(string filePath, DataGridView dgv)
{ //根据路径打开一个Excel文件并将数据填充到DataSet中
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + filePath + ";Extended Properties ='Excel 8.0;HDR=NO;IMEX=1'";//导入时包含Excel中的第一行数据,并且将数字和字符混合的单元格视为文本进行导入
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1"); //根据DataGridView的列构造一个新的DataTable
DataTable tb = new DataTable();
foreach (DataGridViewColumn dgvc in dgv.Columns)
{
if (dgvc.Visible && dgvc.CellType != typeof(DataGridViewCheckBoxCell))
{
DataColumn dc = new DataColumn();
dc.ColumnName = dgvc.DataPropertyName;
dc.DataType = dgvc.ValueType;//若需要限制导入时的数据类型则取消注释,前提是DataGridView必须先绑定一个数据源那怕是空的DataTable
tb.Columns.Add(dc);
}
} //根据Excel的行逐一对上面构造的DataTable的列进行赋值
foreach (DataRow excelRow in ds.Tables[0].Rows)
{
int i = 0;
DataRow dr = tb.NewRow();
foreach (DataColumn dc in tb.Columns)
{
dr[dc] = excelRow[i];
i++;
}
tb.Rows.Add(dr);
}
//在DataGridView中显示导入的数据
dgv.DataSource = tb;
}
conn.Open();这一行
报错:外部表不是预期的格式。
Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source=" + xlsdztb.Text + ";Extended Properties=Excel 12.0";
未处理 System.Data.OleDb.OleDbException
Message="外部表不是预期的格式。"
Source="Microsoft JET Database Engine"
ErrorCode=-2147467259
StackTrace:
在 System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
在 System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
在 System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
在 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
在 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
在 System.Data.OleDb.OleDbConnection.Open()
在 WindowsFormsApplication1.Form1.EcxelToDataGridView(String filePath, DataGridView dgv) 位置 F:\新建文件夹\新建文件夹\WindowsFormsApplication3\WindowsFormsApplication3\Form1.cs:行号 202
在 WindowsFormsApplication1.Form1.toolStripButton4_Click(Object sender, EventArgs e) 位置 F:\新建文件夹\新建文件夹\WindowsFormsApplication3\WindowsFormsApplication3\Form1.cs:行号 187
在 System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
在 System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)
在 System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
在 System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
在 System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
在 System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
在 System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
在 System.Windows.Forms.Control.WndProc(Message& m)
在 System.Windows.Forms.ScrollableControl.WndProc(Message& m)
在 System.Windows.Forms.ToolStrip.WndProc(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.Run(Form mainForm)
在 WindowsFormsApplication1.Program.Main() 位置 F:\新建文件夹\新建文件夹\WindowsFormsApplication3\WindowsFormsApplication3\Program.cs:行号 18
在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Threading.ThreadHelper.ThreadStart()
InnerException:
未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序怎么回事呢? 03的连接写的是对的啊
改成
Extended Properties ='Excel 8.0;HDR=Yes;IMEX=1'
这个连接帮我检查一下
原因 DATAGRIDVIEW TO EXCEL 的表 不能够从新导入DATAGRIDVIEW ,excel 不是标准格式
自己动手写的表 则可以。
网上判断的方法是: 用记事本打开EXCEL 标准格式 显示乱码 而我的不是乱码怎么改进???
private void toolStripButton3_Click_1(object sender, EventArgs e)
{
if (dataGridView1.RowCount > 1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog(); //Windows 窗体 SaveFileDialog 组件是一个预先配置的对话框。它与 Windows 使用的标准“保存文件”对话框相同 saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; //获取或设置筛选器字符串,该字符串确定在 SaveFileDialog 中显示的文件类型 //"Execl files (*.xls)|*.xls"
saveFileDialog.FilterIndex = 0; //索引 saveFileDialog.RestoreDirectory = true;//获取或设置一个值,该值使文件对话框将其当前目录还原为用户更改目录以搜索文件之前的初始值 saveFileDialog.CreatePrompt = true;//获取或设置一个值,该值指示如果用户指定一个不存在的文件,SaveFileDialog 是否提示用户以允许创建文件 saveFileDialog.Title = "Export Excel File To"; //获取或设置在文件对话框的标题栏中显示的文本
//saveFileDialog.ShowDialog();// 显示预置对话框
Stream myStream;//提供字节序列的一般视图,命名空间: System.IO
if (DialogResult.OK == saveFileDialog.ShowDialog())
{
//表示用户正确指定了文件,
//你的代码
myStream = saveFileDialog.OpenFile();//为用户使用 SaveFileDialog 选定的文件名创建读/写文件流
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(0));//用指定的编码及默认缓冲区大小,为指定的流初始化 StreamWriter 类的新实例
string str = "";
try
{
//写标题 for (int i = 0; i < dataGridView1.ColumnCount; i++)
{ if (i > 0)
{ str = str + "\t"; } str = str + dataGridView1.Columns[i].HeaderText; }
sw.WriteLine(str); //写内容 for (int j = 0; j < dataGridView1.Rows.Count; j++)
{ string tempStr = ""; for (int k = 0; k < dataGridView1.Columns.Count; k++)
{ if (k > 0)
{ tempStr += "\t"; // 间隔字符 }
if (dataGridView1.Rows[j].Cells[k].Value == null)
{
tempStr += "";
}
else
{ tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
} } sw.WriteLine(tempStr); } sw.Close(); myStream.Close(); MessageBox.Show("导入完成!"); } catch (Exception E)
{
MessageBox.Show(E.ToString()); }
finally
{
sw.Dispose();
sw.Close();
myStream.Dispose();
myStream.Close();
}
}
}
else
{ MessageBox.Show("没有数据可以导出!", "提示");
}
}
}
datagridview to excel 如上
但不是标准格式
自动生成的excel 无法 再次导入datagridview
原因即为 自动生成的excel 不是标准格式
//从Excel文件中获取数据以填充数据集
public static DataSet GetDataFromExcel(String ExcelFileName)
{
string strConn;
DataSet myDataSet=new DataSet();
try
{
strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ExcelFileName+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection conn=new OleDbConnection(strConn);
OleDbDataAdapter myCommand=new OleDbDataAdapter("SELECT * FROM [Sheet1$] ",strConn);
myCommand.Fill(myDataSet);
conn.Close();
}
catch(Exception ee)
{
DialogResult dr=(new ZB_ERP.Common.Tools.DialogWin("系统提示","从电子表格文件中装载数据异常!",ee.Message)).ShowDialog(null);
}
finally
{
GC.Collect();
}
return myDataSet;
}
http://www.opent.cn/a/092/628.shtml