利用DevExpress.XtraGrid实现Excel 转换成PDF的方法
客官请骚等......代码奉上
private void BtnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Excel文件";
ofd.FileName = "";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//为了获取特定的系统文件夹,可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举,其中可以定义要返回路径的哪个系统目录
ofd.Filter = "所有文件(*.*)|*.*|Excel2003文件(*.xls)|*.xls|Excel2007文件(*.xlsx)|*.xlsx"; //获取或设置筛选器字符串,该字符串确定在 SaveFileDialog 中显示的文件类型
ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
ofd.CheckFileExists = true;//验证路径有效性
ofd.CheckPathExists = true; //验证文件有效性
string strName = string.Empty;
if (ofd.ShowDialog() == DialogResult.OK)
{
strName = ofd.FileName;
}
if (strName == "")
{
MessageBox.Show("没有选择Excel文件!无法进行数据导入");
return;
}
DataSet ds = GetDataFromExcel(strName);
this.gridControl1.DataSource = ds.Tables.DefaultView;
}
public static DataSet GetDataFromExcel(string ExcelFileName)
{
string strConn;
DataSet myDataSet = new DataSet();
try
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM ", strConn);
myCommand.Fill(myDataSet);
conn.Close();
}
catch (Exception ee)
{
XtraMessageBox.Show("从电子表格文件中装载数据异常!", ee.Message);
}
finally
{
GC.Collect();
}
return myDataSet;
}
private void BtnOut_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "导出Excel";
saveFileDialog.FileName = "导出的文件";
saveFileDialog.Filter = "Excel文件(*.pdf)|*.pdf";
DialogResult dialogResult = saveFileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
gridControl1.ExportToPdf(saveFileDialog.FileName);
DevExpress.XtraEditors.XtraMessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
前台页面只需二个按钮和一个gridControl就可以了
当导出的PDF是乱码的解决办法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace CntpyCopy
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
DevExpress.Utils.AppearanceObject.DefaultFont = new System.Drawing.Font("宋体", 9);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new WinFrom());
}
}
}
DevExpress.Utils.AppearanceObject.DefaultFont = new System.Drawing.Font("宋体", 9); //在程序入口地方加上这行就能实现导出不是乱码的问题
页:
[1]