C#在C/S下如何将DataGridView导出Word或Excel?

dayang816 2010-03-12 02:16:22
C#在C/S下如何将DataGridView导出Word或Excel?

本人新手,最好有详细代码,谢谢!
...全文
1431 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
asdweqerzx 2012-09-24
  • 打赏
  • 举报
回复
5楼的方法如何调用?菜鸟求解
Dephy 2010-09-24
  • 打赏
  • 举报
回复
在窗体中如何用Botton调用这个代码,导出dategridview的数据呢?
Hamber_Bao 2010-06-19
  • 打赏
  • 举报
回复
学习` 二楼中的DataTable最好前面加上命名空间

不然,VS会报错 Excel.DataTable和System.Data.DataTable会出现引用不明确错误
傻_吖_头 2010-04-23
  • 打赏
  • 举报
回复
新手上路 不是很熟 请高手相助!!

在导入word 方法中 参数ProgressBar progreesBar 这什么啊?
傻_吖_头 2010-04-23
  • 打赏
  • 举报
回复
那导入 word 的方法呢?
顺便学习一下 (*^__^*) 嘻嘻……
zhushoudong 2010-04-02
  • 打赏
  • 举报
回复
好像DataTable dt = this.dgvWaterTicket.DataSource;
这样是不能复制的 说要要强制什么类型似的
volkswageos 2010-03-27
  • 打赏
  • 举报
回复
这个是导入到word中使用组件的方法

#region 导出当前页DataGridView中的数据到Word中

public void ExportDataGridViewToWord(DataGridView srcDgv, ProgressBar progreesBar, SaveFileDialog sfile)
{
if (srcDgv.Rows.Count == 0)
{
MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
sfile.AddExtension = true;
sfile.DefaultExt = ".doc";
sfile.Filter = "(*.doc)|*.doc";
if (sfile.ShowDialog() == DialogResult.OK)
{
progreesBar.Visible = true;
object path = sfile.FileName;
Object none = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
//建立表格
Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count, srcDgv.Columns.Count, ref none, ref none);
try
{
for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
{
table.Cell(0, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;
}
for (int i = 1; i < srcDgv.Rows.Count; i++)//填充数据
{
for (int j = 0; j < srcDgv.Columns.Count; j++)
{
table.Cell(i + 1, j + 1).Range.Text = srcDgv[j, i - 1].Value.ToString();
}
progreesBar.Value += 100 / srcDgv.RowCount;
}
document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
document.Close(ref none, ref none, ref none);

progreesBar.Value = 100;
MessageBox.Show("数据已经成功导出到:" + sfile.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
progreesBar.Value = 0;
progreesBar.Visible = false;
}
catch(Exception e)
{
MessageBox.Show(e.Message, "友情提示", MessageBoxButtons.OK);
}
finally
{
wordApp.Quit(ref none, ref none, ref none);
}
}
}

}
#endregion
volkswageos 2010-03-24
  • 打赏
  • 举报
回复
[Quote=引用楼主 dayang816 的回复:]
C#在C/S下如何将DataGridView导出Word或Excel?

本人新手,最好有详细代码,谢谢!
[/Quote]

下面是我将dategridview数据导入到excel的方法



#region 导出当前页DataGridView中的数据到Excel中,用流保存成xls文件. 这种方法比较好,不用引用Excel组件
/// <summary>
/// 导出当前页DataGridView中的数据到EXcel中
/// </summary>
/// <param name="dataGridView">dataGridView</param>
/// <param name="progreesBar">progreesBar</param>
public void ExportTOExcelWithoutWidget(DataGridView gridView, ProgressBar progreesBar, SaveFileDialog saveFileDialog) //另存新档按钮 导出成Excel
{
if (gridView.Rows.Count == 0)
{
MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";
saveFileDialog.ShowDialog();
progreesBar.Visible = true;
Stream myStream;
myStream = saveFileDialog.OpenFile();
//StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
//写标题
for (int i = 0; i < gridView.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += gridView.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < gridView.Rows.Count-1; j++)
{
string tempStr = "";
for (int k = 0; k < gridView.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += gridView.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
progreesBar.Value += 100 / gridView.RowCount;
}
sw.Close();
myStream.Close();
progreesBar.Value = 100;
MessageBox.Show("数据已经成功导出到:" + saveFileDialog.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
progreesBar.Value = 0;
progreesBar.Visible = false;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "友情提示", MessageBoxButtons.OK);
}
finally
{
sw.Close();
myStream.Close();
}
}
}
#endregion
volkswageos 2010-03-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 hs1983 的回复:]
using Excel;

在项目中引入Excel.dll


C# code
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
priva……
[/Quote]

使用excel组件在安装的时候不方便的,现在正在寻找导出到word中的方法
wuyq11 2010-03-12
  • 打赏
  • 举报
回复
public static bool ExportForDataGridview(DataGridView gridView, string fileName, bool isShowExcle)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
if (app == null)
{
return false;
}

app.Visible = isShowExcle;
Workbooks workbooks = app.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
if (worksheet == null)
{
return false;
}
string sLen = "";
char H = (char)(64 + gridView.ColumnCount / 26);
char L = (char)(64 + gridView.ColumnCount % 26);
if (gridView.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[gridView.ColumnCount];
for (int i = 0; i < gridView.ColumnCount; i++)
{
asCaption[i] = gridView.Columns[i].HeaderText;
}
ranCaption.Value2 = asCaption;
object[] obj = new object[gridView.Columns.Count];
for (int r = 0; r < gridView.RowCount - 1; r++)
{
for (int l = 0; l < gridView.Columns.Count; l++)
{
if (gridView[l, r].ValueType == typeof(DateTime))
{
obj[l] = gridView[l, r].Value.ToString();
}
else
{
obj[l] = gridView[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(fileName);
workbook.Saved = true;
}
finally
{
app.UserControl = false;
app.Quit();
}
return true;

}
private void SaveAs()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true
saveFileDialog.Title = "";
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{

for (int i = 0; i < dgv.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dgv.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dgv.Columns.Count; k++)
{
if (k > 0)

{
tempStr += "\t";
}
tempStr += dgv.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}

}

Excel.Application myexcel = new Excel.Application();
Excel.Workbook mybook = default(Excel.Workbook);
Excel.Worksheet mysheet = default(Excel.Worksheet);
mybook = myexcel.Workbooks.Add("ExcelFilename");
mysheet = mybook.Worksheets("sheet1");
mysheet.Activate();
mysheet.Range("A1").Select();
DataGridView.SelectAll();
System.Windows.Forms.DataObject t = new System.Windows.Forms.DataObject();
t = dv.GetClipboardContent();
System.Windows.Forms.Clipboard.SetDataObject(t);
mysheet.PasteSpecial(Format = "文本", Link = false, DisplayAsIcon = false);
mengxj85 2010-03-12
  • 打赏
  • 举报
回复
UP
[Quote=引用 1 楼 hs1983 的回复:]
using Excel;

在项目中引入Excel.dll


C# code
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
priva……
[/Quote]
hs1983 2010-03-12
  • 打赏
  • 举报
回复
using Excel;

在项目中引入Excel.dll

/// <summary>
/// 导出Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExportExcel_Click(object sender, EventArgs e)
{
DataTable dt = this.dgvWaterTicket.DataSource;
if (dt == null)
{
return;
}
if (dt.Rows.Count == 0)
{
return;
}
Excel.Application xlApp = new Excel.Application();
if (xlApp == null)
{
MessageBox.Show("请确保您的电脑已经安装Excel", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
xlApp.UserControl = true;
Excel.Workbooks workbooks = xlApp.Workbooks;
//根据模版产生新的workbook //Workbook workbook = workbooks.Add("D:\\aa.xls");
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
if (worksheet == null)
{
MessageBox.Show("请确保您的电脑已经安装Excel", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{

Excel.Range range;
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
worksheet.Cells[1, 1] = frm.Text;//导出的标题
worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, dt.]).MergeCells = true; //合并单元格---列数
worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, 3]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//居中对齐
worksheet.get_Range(worksheet.Cells[1, 3], worksheet.Cells[1, 3]).ColumnWidth = 15; //列宽
worksheet.get_Range(worksheet.Cells[1, 2], worksheet.Cells[1, 2]).ColumnWidth = 15; //列宽
worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, 1]).ColumnWidth = 20; //列宽

//写入字段
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
range = (Excel.Range)worksheet.Cells[2, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;

}
//写入数值

for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i];
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
//System.Threading.Thread.Sleep(500);
//如果字的数量过多则自动换行。worksheet.Cells[r+1, 4]为worksheet.Cells[行, 列]
worksheet.get_Range(worksheet.Cells[r + 3, 4], worksheet.Cells[r + 1, 4]).Columns.WrapText = true; //自动换行
worksheet.get_Range(worksheet.Cells[r + 3, 4], worksheet.Cells[r + 3, 4]).Rows.AutoFit(); //自动加行高
//this.Text = "导出数据[" + percent.ToString("0.00") + "%]...";

}

range = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]);
range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);

range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;

if (dt.Columns.Count > 1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
}

xlApp.Visible = true;

}
catch
{
MessageBox.Show("到出Excel失败!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
finally
{

System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);

System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);

System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);

System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
//KillProcess("Excel");
GC.Collect();//强行销毁
}
}
DataGridView打印控件和.NET打印控件5.7版2014年11月2日修改完成,完全免费,在.NET2.0及以上环境下都可以使用(VB打印、C#打印都是可以的),有帮助文档与使用实例。 与上一版相比,控件5.7版的主要更改如下: 1、重写DataGridView导出Excel的代码,5.7版控件使用开源的NPOI库导出Excel,完全不依赖Office,不会再有因为没装Office或Office安装有问题而导出失败的情况,而且导出速度非常快,支持大于65536条记录的导出(自动分成多个工作表),效果非常好。导出Excel的接口未变,因此您不需要修改任何代码,只需替换控件即可; 2、SimpleReport打印组件添加了导出Excel功能,该功能在打印预览界面的按钮中; 3、多表头组件MulHeaderDataGridView添加了从Excel中导入数据(ImportFromExcel函数)及复制(Copy函数)与粘贴(Paste函数)的功能。其中导入Excel功能使用开源的NPOI组件实现,不依赖Office。 4、其他一些完善,比如解决了导出Excel时强制换行不自动显示,而是要双击才显示问题;导出Excel时,图片能按单元格大小导出。 本控件特色: 1、强大的DataGridView打印功能,不仅可以以多种形式(普通打印、分栏打印、跨页打印、工资条打印)打印DGV表格,基本上能完全按DGV控件本身设置的格式如字体、字号、背景颜色、前景颜色、单元格对齐方式等打印出来,文字图像都可以打印,而且是完全根据表格当前的显示顺序进行打印的,基本上做到了所见即所得的打印。 2、报表设计功能。报表模板设计组件EasyReport可以设计普通报表、分组报表、套打模板等,以DataGridView为数据源。控件的位置以毫米为计量单位,定位准确,很适合套打单据设计。 3、强大的图表打印功能。5.2版控件新增了一个Chartlet的组件,使用非常方便,可以生成柱形图、饼图、折线图等多种图形,而且可以设置2D或3D效果,既可以在打印控件中打印出来,也可以在Graphics对象中显示。 4、分组汇总打印DataGridVeiw功能,每组还可以自动换新页打印,还可以自动增加行号。 5、强大的文本打印输出功能,控件提供多个文本打印重载函数,打印文本时,如果需要,控件会自动换行和换页打印输出。还增加了以指定行间距及字符间距打印文本的功能,可以用固定行距,也可以用单倍或多倍行距打印文本。 6、强大的绘图功能,基本上.NET的GDI+的绘图函数(如直线、矩形、路径、多边形、曲线等)都有,只有个别函数的名称有点区别。 7、支持同一文档多种版面格式打印(类似于Word中的节的功能):对同一份文档,不同的页面可以设置不同的格式(纸张大小、纸张方向、页边距),只需要在新增一页时在NewPage方法中指定要使用的页面格式即可,使用非常简单。 8、报表文件保存功能。本控件允许将当前打印预览的内容保存为报表文件,以后使用本控件重新打开该报表文件即可重现原来保存报表时的打印内容。 9、Excel导出功能,可以将DataGridView导出Excel文件,5.7版控件使用开源的NPOI导出Excel,速度非常快,效果非常好,5.4版还增加了合并单元格的导出功能。 10、打印DataGridView时的打印方案保存与读取功能。可以将当前打印参数保存为打印方案文件,或者从保存的打印方案文件中读取打印参数。 11、水印打印功能。根据需要,可以在页面中打印或不打印以半透明空心文字打印水印。 12、强大的容器控件打印功能(DrawPanel函数)。借助该函数,您只需要在您的容器控件中设计好要打印的内容及打印内容的相对位置,控件轻松帮你打印出来(如果超过一页,控件会自动换页续打)。 13、特殊文字效果打印功能。控件具有打印浮雕文字、阴影文字、空心文字、块文字的功能。 14、页眉页脚中既可打印文字,也可打印图像,或者即打印图像又打印输出文字。 15、图像与图标打印输出功能。 16、多表头(跨行跨列的复杂表头)打印功能,多表头组件支持多表头显示与打印、单元格内容的合并显示、打印与导出。 17、自定义纸张支持功能。 18、纸张背景图片设置打印功能。 19、.NET4.0支持功能(是单独的一个文件)。 20、直接打印窗口中的TreeView控件功能。 21、打印窗口中的ListView功能。 22、RichTextBox控件的RTF文本打印功能。 23、斜线表头打印功能(5.4版新增)。 24、二维码打印功能(5.5版本增加)。 25、5.6版新增的SimpleReport组件允许您在一个方案文件中管理多个打印方案,在打印预览时能自由在各个打印方案之间切换。 26、5.7版控件增加了使用开源的NPOI从Excel文件中导入数据到DataGridView的功能,以及DataGridView的复制与粘贴功能。 我将持续改进该控件,并将不断推出控件的新版本,要查看或下载控件的升级版本,请登陆网站:http://myyouping.download.csdn.net/ 。具体使用方法请参见帮助文件与实例文件,如有疑问或好的建议,请与我联系: 邮箱:myyouping@139.com Q Q:479781502

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧