❶ 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了。、