1、初始化导出格式下来框,目前提供的有html,pdf,excel txt 等各种方式。
初始化函数如下:
void InitExportData() {
for(int i = 0; i < exportData.GetLength(0); i++)
cbExport.Properties.Items.Add(exportData.GetValue(i, 0));
cbExport.SelectedIndex = 0;
}
cbexport 为对应combox下拉框控件。
加黑的exportData为几种格式。
2.初始化下拉框内容:
string[,] exportData = new string[,] {{"HTML Document", "HTML Documents|*.html", "htm"},
{"Microsoft Excel 2007 Document", "Microsoft Excel|*.xlsx", "xlsx"},
{"Microsoft Excel Document", "Microsoft Excel|*.xls", "xls"},
{"RTF Document", "RTF Files|*.rtf", "rtf"},
{"PDF Document", "PDF Files|*.pdf", "pdf"},
{"MHT Document", "MHT Files|*.mht", "mht"},
{"Text Document", "Text Files|*.txt", "txt"}};
3、导出按钮如下:
int index = cbExport.SelectedIndex;
if(index < 0) return;
string fileName = ShowSaveFileDialog(exportData.GetValue(index, 0).ToString(), exportData.GetValue(index, 1).ToString());
if(fileName == string.Empty) return;
ExportToEx(fileName, exportData.GetValue(index, 2).ToString(), gridView1);
OpenFile(fileName);
4、其中调用的函数如下:
private string ShowSaveFileDialog(string title, string filter) {
SaveFileDialog dlg = new SaveFileDialog();
string name = Application.ProductName;
int n = name.LastIndexOf(".") + 1;
if(n > 0) name = name.Substring(n, name.Length - n);
dlg.Title = "Export To " + title;
dlg.FileName = name;
dlg.Filter = filter;
if(dlg.ShowDialog() == DialogResult.OK) return dlg.FileName;
return "";
}
private void ExportToEx(String filename, string ext, BaseView exportView) {
Cursor currentCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
if(ext == "rtf") exportView.ExportToRtf(filename);
if(ext == "pdf") exportView.ExportToPdf(filename);
if(ext == "mht") exportView.ExportToMht(filename);
if(ext == "htm") exportView.ExportToHtml(filename);
if(ext == "txt") exportView.ExportToText(filename);
if(ext == "xls") exportView.ExportToXls(filename);
if(ext == "xlsx") exportView.ExportToXlsx(filename);
Cursor.Current = currentCursor;
}
5、导出文件后,提示是否打开当前导出的文件函数
private void OpenFile(string fileName) {
if(XtraMessageBox.Show("是否打开?", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
try {
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = fileName;
process.StartInfo.Verb = "Open";
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.Start();
}
catch {
}
}
}