❶ C#winform中如何把表導出到EXCEL
我們一般用的方法是將表遍歷一遍,然後寫入到excel中,主要代碼如下: ///顫塵 <summary>
/// 指定文件名稱、表名、DataGridView導出DataGridView中的數據到Excel中
/// </summary>
/// <param name="location">輸出文件的位置<派燃/param>
/// <param name="tableName">表名</param>
/// <param name="dt"塵洞虛>DataGridView名稱</param>
public void GridViewToExcel(string location, string tableName, DataGridView dt)
{
Stream myStream;
myStream = File.Open(location,FileMode.Create);
//StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
int m=0;
try
{
//寫標題
for (int i = 0; i < dt.ColumnCount; i++)
{
if (dt.Columns[i].Visible == false)
{
continue;
}
else
{
str += dt.Columns[i].HeaderText + "\t";
}
} //string aa = str.Substring(0, str.Length - 1);
sw.WriteLine(str.Substring(0,str.Length-1)); //寫內容
for (int j = 0; j < dt.Rows.Count; j++)
{
if (dt.Rows[j].Visible == true)
{
string tempStr = "";
for (int k = 0; k < dt.Columns.Count; k++)
{
if (dt.Columns[k].Visible == false)
{
continue;
}
else
{
tempStr += dt.Rows[j].Cells[k].Value.ToString() + "\t";
}
} sw.WriteLine(tempStr.Substring(0,tempStr.Length-1));
}
}
sw.Close();
myStream.Close();
} catch (Exception e)
{
MessageBox.Show(e.ToString());
} finally
{
sw.Close();
myStream.Close();
}
}
❷ 在winform中怎麼做Excel的模板,然後再導出數據
private void exp()
{
try
{
SaveFileDialog sdf = new SaveFileDialog();
sdf.Title = "EXECL文件";
sdf.Filter = "EXECL文件(*.xls) |*.xls |所有文件(*.*) |*.*";
if (sdf.ShowDialog() != DialogResult.OK)
{
return;
}
WaitFormService.Current.CreateWaitForm();
ExcelHelper excel = new ExcelHelper(sdf.FileName);
excel.Create("商品");
excel.SetCellValue(1, 1, ""); //搭粗導出知哪鎮以後再EX中的列名···下面一樣的·你要導出幾個列就寫幾個緩扒
excel.SetCellValue(1, 2, "");
excel.SetCellValue(1, 3, "");
excel.SetCellValue(1, 4, "");
int row_Start = 2;
foreach (DataGridViewRow row in DataGridView1.Rows)
{
excel.SetCellNumberFormatLocal(row_Start, 1, "@");
excel.SetCellValue(row_Start, 1, row.Cells["code"].Value); 在就是往裡面對應的填充列名咯
excel.SetCellValue(row_Start, 2, row.Cells["Good"].Value);
excel.SetCellValue(row_Start, 3, row.Cells["name"].Value);
excel.SetCellNumberFormatLocal(row_Start, 4, "@");
excel.SetCellValue(row_Start, 5, row.Cells["Amount"].Value);
row_Start++;
}
excel.SetColumnFit();
excel.SetBorder();
excel.Save();
excel.Exit();
WaitFormService.Current.CloseWaitForm();
MessageBox.Show("導出成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
這個是導出的方法··你到時候直接建個控制項然後丟控制項單擊事件裡面
❸ 如何使用c#將Winform下DataGridView中內容導出到Excel
C#操作EXCEL全解橋洞橡(代碼)
提示:運行之前必須先引用Interop.Excel.dll模塊
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Reflection;
using Excel;
namespace AnalysisSystem.DB
{
public class ExcelOperation
{
PRivate string _fileName;/顫明/保存路徑名
public ExcelOperation(string fileName)
{
_fileName = fileName;
}
private OleDbConnection GetConnection()
{
string connectString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0"敏旁,_fileName);
OleDbConnection myConn = new OleDbConnection(connectString);//建立鏈接
return myConn;
}
public System.Data.DataTable ExecuteTableResult(string strSql)
{
System.Data.DataTable dt = new System.Data.DataTable();
try
{
OleDbConnection conn = this.GetConnection();
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);//執行相關SQL語句
da.Fill(dt);
}
catch (System.Exception ex)
{
//do nothing
}
return dt;
}
public DataSet ExecuteSetResult(string strSql,string table_name)
{
DataSet ds = new DataSet();
string temp_name = "[" + table_name + "$]";
try
{
OleDbConnection conn = this.GetConnection();
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
da.Fill(ds,temp_name);
}
catch (System.Exception ex)
{
//do nothing
}
return ds;
}
public string ExecuteOneResult(string strSql)
{
string result = "";
System.Data.DataTable dt = new System.Data.DataTable();
try
{
OleDbConnection conn = this.GetConnection();
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
da.Fill(dt);
}
catch (System.Exception ex)
{
//do nothing
}
if (dt != null && dt.Rows.Count > 0)
{
result = dt.Rows[0][0].ToString();
}
return result;
}
public void ExecuteNonResult(string strSql)
{
try
{
OleDbConnection conn = this.GetConnection();
OleDbCommand cmd = new OleDbCommand(strSql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
//do nothing
}
}
private _Workbook W_B(Excel.application app)
{
Workbooks workbooks = app.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
return workbook;
}
private _Worksheet W_S(_Workbook work_book)
{
Sheets sheets = work_book.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);//獲取選擇第一個表,本身默認名稱為Sheet1
return worksheet;
}
//從DataGridView中導出數據到Excel表,單表導出
public void Excel_out(DataGridView dataGridView1)
{
//建立Excel對象
Excel.Application app = new Excel.Application();
try
{
_Workbook workbook = this.W_B(app);
_Worksheet worksheet = this.W_S(workbook);
string sLen = "";
//取得最後一列列名
char H = (char)(64 + dataGridView1.ColumnCount / 26);
char L = (char)(64 + dataGridView1.ColumnCount % 26);
if (dataGridView1.ColumnCount < 26)
{
sLen = L.ToString();
}
else
{
sLen = H.ToString() + L.ToString();
}
//標題
string sTmp = sLen + "1";
Range ranCaption = worksheet.get_Range(sTmp, "A1");
string[] asCaption = new string[dataGridView1.ColumnCount];
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
asCaption[i] = dataGridView1.Columns[i].HeaderText;
}
ranCaption.Value2 = asCaption;
//數據
object[] obj = new object[dataGridView1.Columns.Count];
for (int r = 0; r < dataGridView1.RowCount - 1; r++)
{
for (int l = 0; l < dataGridView1.Columns.Count; l++)
{
if (dataGridView1[l, r].ValueType == typeof(DateTime))
{
obj[l] = dataGridView1[l, r].Value.ToString();
}
else
{
obj[l] = dataGridView1[l, r].Value;
}
}
string cell1 = sLen + ((int)(r + 2)).ToString();
string cell2 = "A" + ((int)(r + 2)).ToString();
Range ran = worksheet.get_Range(cell1, cell2);
ran.Value2 = obj;
}
//保存
workbook.SaveCopyAs(this._fileName);
workbook.Saved = true;
}
finally
{
//關閉
app.UserControl = false;
app.Quit();
}
}
/// <summary>
/// 多表導出
/// </summary>
/// <param name="dataGridView">DataGridView列表集合</param>
/// <param name="TableList">表名稱集合</param>
public void Excel_out_MulTable(List<DataGridView> dataGridView, string[] TableList)
{
//建立Excel對象
Excel.Application app = new Excel.Application();
try
{
Workbooks workbooks = app.Workbooks;//定義一個工作簿集合
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);//向工作簿添加一個新工作簿
Sheets sheets = workbook.Worksheets;//定義一個工作表集合
_Worksheet worksheet ;
int wnumber = 0;
while (wnumber++ < (TableList.GetLength(0) - 1))
{
sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);//向一個工作表集合添加一個新工作表
}
/*提醒:Missing類為命名空間System.Reflection中的類,所以記得引入*/
wnumber = 0;
foreach (DataGridView dataGridView1 in dataGridView)
{
worksheet = null;
worksheet = (_Worksheet)sheets.get_Item(wnumber + 1);//取出需要進行操作的工作表
worksheet.Name = TableList[wnumber];//設置改工作表名稱
if (wnumber != 0)
sheets.Select(wnumber);//選中操作表
string sLen = "";
//取得最後一列列名
char H = (char)(64 + dataGridView1.ColumnCount / 26);
char L = (char)(64 + dataGridView1.ColumnCount % 26);
if (dataGridView1.ColumnCount < 26)
{
sLen = L.ToString();
}
else
{
sLen = H.ToString() + L.ToString();
}
//標題
string sTmp = sLen + "1";
Range ranCaption = worksheet.get_Range(sTmp, "A1");
string[] asCaption = new string[dataGridView1.ColumnCount];
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
asCaption[i] = dataGridView1.Columns[i].HeaderText;
}
ranCaption.Value2 = asCaption;
//數據
object[] obj = new object[dataGridView1.Columns.Count];
for (int r = 0; r < dataGridView1.RowCount - 1; r++)
{
for (int l = 0; l < dataGridView1.Columns.Count; l++)
{
if (dataGridView1[l, r].ValueType == typeof(DateTime))
{
obj[l] = dataGridView1[l, r].Value.ToString();
}
else
{
obj[l] = dataGridView1[l, r].Value;
}
}
string cell1 = sLen + ((int)(r + 2)).ToString();
string cell2 = "A" + ((int)(r + 2)).ToString();
Range ran = worksheet.get_Range(cell1, cell2);//設置單元格
ran.Value2 = obj;
}
wnumber++;
}
//保存
workbook.SaveCopyAs(this._fileName);
workbook.Saved = true;
}
finally
{
//關閉
app.UserControl = false;
app.Quit();
}
}
}
}
❹ 如何使用c#將Winform下DataGridView中內容導出到Excel
需要使用插件,
1、微軟的EXCEL插件,(DLL) ,需要運行程序的機器上安裝的有對應版本的EXCEL,慢。
2、NPOI(第三方),不需要其他約束,二進制處理,極快。
兩種插件思路都是按照 單元格來處理EXCEL讀寫,可以自己查詢文檔,很簡單的。
比如
var st1 = wk.GetSheetAt(0);// EXCEL的第一個sheet。
var row = st1.GetRow(0);//該sheet的第一行。
var cell = row.GetCell(0); //該行的第一個單元格,
然後就是賦值了,
cell.SetCellValue = "你要賦的值";
然後吵純遍歷整個sheet 就OK了。
最後存起來。
using (Stream s = File.OpenWrite(Path+".xlsx"))
{
wk.Write(s);
}
DataGrid其實格式和Excel一樣的, 你一次取一行,然後從第一列開始遍歷灶虧,給EXCEL賦值就好了.
var value = Mydatagrid.Row[i][j]; 其實就是個數據表,分別指定行數和列數,就取出來值了。
自己轉換一下數據升辯咐類型,給EXCEL就OK了。、