前言:参与了一个小项目,需要导出excel,写写这里面的收获。
内容:
话不多说直接上代码,不,还是要说一句,这个代码在网上查找并改的,因为自己后加的部分所以有一点的冗余,嘻嘻,不多说了看看大家发现了没有 ~ ~ !希望可以得到改正的意见。
private void btnCheckOut_Click(object sender, EventArgs e)
{
if (txtHistory.Text == "没有想要的数据!")
{
MessageBox.Show("没有数据,不能导出");
}
else
{
#region 直接导出Excel
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "xls"; //设置默认扩展名为xls
sfd.Filter = "Excel文件(*.xls)|*.xls";//另存文件时文件类型框中出现的内容
if (sfd.ShowDialog() == DialogResult.OK) //获取选定的另存文件对话框存在
{
DoExport(this.txtHistory, sfd.FileName);
}
#endregion
}
}
//导出文本文件
private void Importtxtfile()
{
SaveFileDialog saveFile1 = new SaveFileDialog();//导出文本文件
saveFile1.Filter = "文本文件(.txt)|*.txt";
saveFile1.FilterIndex = 1;
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK && saveFile1.FileName.Length > 0)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFile1.FileName, false);
try
{
sw.WriteLine(txtHistory.Text); //只要这里改一下要输出的内容就可以了
}
catch
{
throw;
}
finally
{
sw.Close();
}
}
}
//导出excel
private void DoExport(RtfRichTextBox textbox, string strFileName)
{
// string[] lines = System.Text.RegularExpressions.Regex.Split(textbox.Text, "/r/n");
// int rowNum = lines.Length;//获取 TextBox2控件里的数据行数
int rowNum = textbox.Lines.Length; //读取Textbox控件里数据的行数
int rowIndex = 1; //定义一个Excel行
int col = 1; //定义一个Excel列,默认为1
if (rowNum == 0 || string.IsNullOrEmpty(strFileName)) //控件里没有数据
{
MessageBox.Show("没有数据,不能导出");
return;
}
if (rowNum > 0)//控件里有数据
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的系统未安装Excel");
Importtxtfile();
}
xlApp.DefaultFilePath = "";//出现异常
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
for (int i = 0; i < rowNum; i++)//将数据导入Excel
{
string ss = textbox.Lines[i].ToString(); //读取相对应行的数据,这里只是测试用
rowIndex++;
xlApp.Cells[rowIndex, col] = Convert.ToString(textbox.Lines[i].ToString()) + "\t";//读取到的Textbox控件里的数据导入到Excel
//xlApp.Rows[rowIndex,0] = Convert.ToString(textbox.Lines[i].ToString()) + "\t";
}
xlBook.SaveAs(strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlApp = null;
xlBook = null;
MessageBox.Show("数据导出成功!!");
}
}2.我遇到的问题
(1.) 未引用 引用的Microsoft.Office.Interop.Excel(程序集扩展)会提示错误,cs0234 他的属性中有一个嵌入互操作类型 值改为false
(2.) 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Excel._Application”。此操作失败的原因是对 IID 为“{000208D5-0000-0000-C000-000000000046}”的接口的 COM 组件调用 QueryInterface 因以下错误而失败: 加载类型库/DLL 时出错。 (异常来自 HRESULT:0x80029C4A (TYPE_E_CANTLOADLIBRARY))。
这个错误需要恢复一下本机的office 。
总结:遇到问题的时候不要害怕检查具体问题是什么,多查解决的办法总会解决的。
导出Excel与文本文件
本文介绍了如何使用C#从RichTextBox控件中导出数据到Excel和文本文件的方法,并分享了实现过程中遇到的问题及解决方案。
5245





