1、讀取Excel數(shù)據(jù)并寫入到SQLServer數(shù)據(jù)庫(kù)中;
2、將SQLServer數(shù)據(jù)庫(kù)中的數(shù)據(jù)寫入到Excel表中;
以下部分程序代碼:
public void printAll(DataGridView dgv)
{
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "導(dǎo)出Excel (*.xlsx)|*.xlsx";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "導(dǎo)出文件保存路徑";
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
if (strName.Length != 0)
{
//沒有數(shù)據(jù)的話就不往下執(zhí)行
if (dgv.Rows.Count == 0)
return;
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;//若是true,則在導(dǎo)出的時(shí)候會(huì)顯示EXcel界面。
if (excel == null)
{
MessageBox.Show("EXCEL無(wú)法啟動(dòng)!", "錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Workbooks books = excel.Workbooks;
Workbook book = books.Add(miss);
Worksheet sheet = (Worksheet)book.ActiveSheet;
sheet.Name = "Sheet1";
//生成Excel中列頭名稱
for (int i = 0; i < dgv.Columns.Count; i++)
{
if (dgv.Columns[i].Visible == true)
{
excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;
}
}
//把DataGridView當(dāng)前頁(yè)的數(shù)據(jù)保存在Excel中
sheet.SaveAs(strName, miss, miss, miss, miss, miss, 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)成功導(dǎo)出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(strName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "導(dǎo)出失敗!");
}
}
?完整代碼程序及配套測(cè)試數(shù)據(jù)庫(kù)數(shù)據(jù)如下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-602022.html
https://download.csdn.net/download/XueJiaoKui/85331183https://download.csdn.net/download/XueJiaoKui/85331183文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-602022.html
到了這里,關(guān)于C#將數(shù)據(jù)庫(kù)數(shù)據(jù)導(dǎo)出到Excel & 將Excel文件導(dǎo)入到數(shù)據(jù)庫(kù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!