誰能給我發(fā)關于何使用winform導入導出excel方法具體實現(xiàn)winform有表格直接和excel關聯(lián)關于數(shù)據(jù)庫導出excel種excel嵌入winform需要窗口切換要用控件
調(diào)試錯誤下希望高手幫忙
命名空間Microsoft.Office存類型或命名空間名稱Interop(缺少程序集引用?) D:\vs\Excel\Excel\Form1.cs
錯誤該解決
首先 先確定安裝了EXCEL沒有安裝了
VS能會自動添加組件 也能沒有添加
沒關系 因組件自己添加
第步 添加引用 也添加組件 所有解決方案里都有引用文件夾
里點擊添加引用 會看選項卡界面 點擊瀏覽
把excel文件夾下 Microsoft.Office.Interop.Excel.dll組件添加進去
再cs文件還得寫 using Microsoft.Office.Interop.Excel;
之具體導入EXCEL 或 導出代碼了 我里做了導入EXCEL 給吧
希望能幫
public void ExportTOExcel()
{
if (dbgname.Rows.Count == 0)
{
MessageBox.Show("沒有數(shù)據(jù)供導出", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "導出文件保存路徑";
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
if (strName.Length != 0)
{
ToolStripProgressBar toolStripProgressBar1 = new ToolStripProgressBar();
toolStripProgressBar1.Visible = true;
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
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 = "test";
//生成字段名稱
for (int i = 0; i < dbgname.ColumnCount-8; i++)
{
excel.Cells[1, i + 1] = dbgname.Columns[i].HeaderText.ToString();
}
//填充數(shù)據(jù)
for (int i = 0; i < dbgname.RowCount - 1; i++)
{
for (int j = 0; j < dbgname.ColumnCount - 8; j++)
{
if (dbgname[j, i].Value == typeof(string))
{
excel.Cells[i + 2, j + 1] = "" + dbgname[i, j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dbgname[j, i].Value.ToString();
}
}
toolStripProgressBar1.Value += 100 / dbgname.RowCount;
}
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("數(shù)據(jù)已經(jīng)成功導出:" + saveFileDialog.FileName.ToString(), "導出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
toolStripProgressBar1.Value = 0;
toolStripProgressBar1.Visible = false;
}
}
聯(lián)系客服