实例介绍
【实例简介】
大量文档打印前,统计word和Excel的页数
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.Threading;
using Office = Microsoft.Office.Core;
using System.Reflection;
namespace QQTools
{
public partial class FrmPagesStatistics : Form
{
private PageSizes m_PageSize;
List<List<string>> table = new List<List<string>>();
public delegate void RefreshStatusDelegate(string status, int maximum, int inc, string progress);
public delegate void ChangeButtonStateDelegate(Button owner, bool state);
public delegate void RefreshGridViewDelegate();
public delegate void AddDataIntoGridViewDelegate(List<List<string>> rows);
public FrmPagesStatistics()
{
InitializeComponent();
ArrangeGrid();
m_PageSize = new PageSizes();
m_PageSize.LoadPages();
LoadPages();
//table.Columns.Add("序号", typeof(string));
//table.Columns.Add("文件", typeof(string));
//table.Columns.Add("页数", typeof(string));
//table.Columns.Add("备注", typeof(string));
//dataGridView1.DataSource = table;
//dataGridView1.Columns["序号"].Width = 60;
//dataGridView1.Columns["文件"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
//dataGridView1.Columns["页数"].Width = 60;
//dataGridView1.Columns["备注"].Width = 100;
}
private void LoadPages()
{
cboPageList.Items.AddRange(m_PageSize.ToArray());
}
private void chkCustomize_CheckedChanged(object sender, EventArgs e)
{
}
private void cboPageList_Click(object sender, EventArgs e)
{
chkCustomize.Checked = false;
}
private void Custumize_Click(object sender, EventArgs e)
{
chkCustomize.Checked = true;
}
private void btnSavePage_Click(object sender, EventArgs e)
{
float width, height;
if (!float.TryParse(txtWidth.Text, out width)
|| !float.TryParse(txtHeight.Text, out height))
{
Common.ErrDlg(this, "纸张高度和宽度必须是数字");
return;
}
if ((string)cboUnit.SelectedItem == null)
{
Common.ErrDlg(this, "必须指定纸张大小的单位");
return;
}
string name = txtHeight.Text.Trim();
if (name != "")
{
name = "自定义";
}
PageSize pageSize = new PageSize(name, width, height, (string)cboUnit.SelectedItem);
if (m_PageSize.AddPage(pageSize))
{
cboPageList.Items.Add(pageSize);
cboPageList.SelectedItem = pageSize;
m_PageSize.Save();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (Common.ConfirmDlg(this, "确实要删除选定项吗?") == System.Windows.Forms.DialogResult.Yes)
{
ListBox.SelectedObjectCollection items = lstFiles.SelectedItems;
for (int i = items.Count - 1; i >= 0; i--)
{
lstFiles.Items.Remove(items[i]);
}
}
}
private void btnAddFiles_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Word,Excel,pdf文档|*.doc;*.docx;*.xls;*.xlsx;*.pdf|所有文件(*.*)|*.*";
dlg.Multiselect = true;
dlg.CheckFileExists = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
List<string> files = new List<string>();
foreach (string item in lstFiles.Items)
{
files.Add(item);
}
foreach (string file in dlg.FileNames)
{
if (files.IndexOf(file) > -1)
continue;
files.Add(file);
}
files.Sort();
lstFiles.Items.Clear();
lstFiles.Items.AddRange(files.ToArray());
}
}
private void SortList()
{
List<string> files = new List<string>();
foreach (string item in lstFiles.Items)
{
files.Add(item);
}
files.Sort();
lstFiles.Items.Clear();
lstFiles.Items.AddRange(files.ToArray());
}
private void btnAddFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
string path = dlg.SelectedPath;
List<string> files = new List<string>();
foreach (string item in lstFiles.Items)
{
files.Add(item);
}
if (files.IndexOf(dlg.SelectedPath) == -1)
files.Add(path);
files.Sort();
lstFiles.Items.Clear();
lstFiles.Items.AddRange(files.ToArray());
}
}
private void btnClear_Click(object sender, EventArgs e)
{
if (Common.ConfirmDlg(this, "确实要清空列表吗?") == System.Windows.Forms.DialogResult.Yes)
lstFiles.Items.Clear();
}
List<string> searchedFiles = new List<string>();
int fileCount;
int pageCount;
List<string> wordDocExts = new List<string>(new string[] { ".doc", ".docx" });
List<string> excelExts = new List<string>(new string[] { ".xls", ".xlsx" });
private bool threadSignal_Do_Next = true;
Thread thread = null;
private void btnDo_Click(object sender, EventArgs e)
{
threadSignal_Do_Next = true;
tsProgressBar.Value = 0;
tsProgressBar.Minimum = 0;
btnDo.Enabled = false;
btnStop.Enabled = true;
table.Clear();
listView1.Items.Clear();
thread = new Thread(new ParameterizedThreadStart(StartisticsThread));
thread.IsBackground = true;
thread.Start(new object[] { chkWord.Checked, chkExcel.Checked, chkPDF.Checked, chkIncludeSubFolder.Checked, lstFiles.Items });
//Statistics(chkWord.Checked,chkExcel.Checked,chkPDF.Checked,chkIncludeSubFolder.Checked);
}
private void StartisticsThread(object parameters)
{
object[] ps = (object[])parameters;
bool word = (bool)ps[0];
bool excel = (bool)ps[1];
bool pdf = (bool)ps[2];
if (word == false && excel == false && pdf == false)
{
Common.InfoDlg(this, "没有选择任何处理类型");
return;
}
bool includeSubFolder = (bool)ps[3];
ListBox.ObjectCollection file_Folders = (ListBox.ObjectCollection)ps[4];
Statistics(word, excel, pdf, includeSubFolder,file_Folders);
}
public bool IsTempFile(string file)
{
string fileName=System.IO.Path.GetFileName(file);
if (fileName.StartsWith("~$") && (File.GetAttributes(file) & FileAttributes.Hidden) == FileAttributes.Hidden)
return true;
else
return false;
}
private void Statistics(bool word, bool excel, bool pdf, bool includeSubFolder,ListBox.ObjectCollection file_Folders)
{
pageCount = 0;
fileCount = 0;
searchedFiles.Clear();
List<string> filesToStatistics = new List<string>();
foreach (string item in file_Folders)
{
if (File.Exists(item) && !IsTempFile(item))
{
string extName = Path.GetExtension(item);
if (excel && excelExts.IndexOf(extName) > -1
|| word && wordDocExts.IndexOf(extName) > -1
||pdf&&".pdf".Equals(extName))
{
if (filesToStatistics.IndexOf(item) == -1)
filesToStatistics.Add(item);
}
}
else if (Directory.Exists(item))
{
string[] files = Directory.GetFiles(item, "*.*", includeSubFolder? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
if (!IsTempFile(file))
continue;
string extName = Path.GetExtension(file);
if (word && (wordDocExts.IndexOf(extName) > -1) && filesToStatistics.IndexOf(file) == -1)
filesToStatistics.Add(file);
else if (excel && (excelExts.IndexOf(extName) > -1) && filesToStatistics.IndexOf(file) == -1)
{
filesToStatistics.Add(file);
}
else if (pdf && ".pdf".Equals(extName))
{
filesToStatistics.Add(file);
}
if (!threadSignal_Do_Next)
return;
}
}
if (!threadSignal_Do_Next)
return;
}
filesToStatistics.Sort();
Microsoft.Office.Interop.Excel.Application excelApp = null;
Excel.Workbooks books = null;
Word.Application wordApp = null;
Word.Documents wordDocuments = null;
try
{
RefreshStatus("",filesToStatistics.Count, 0, "");
int progress = 0;
//dataGridView1.Rows.Clear();
table.Clear();
Application.DoEvents();
foreach (string file in filesToStatistics)
{
RefreshStatus(file, filesToStatistics.Count, 0,string.Concat( progress, "/", filesToStatistics.Count));
int count = -1;
string extName = Path.GetExtension(file);
if (extName != null)
extName = extName.ToLower();
if (word && wordDocExts.IndexOf(extName) > -1)
{
if (wordApp == null)
{
wordApp = new Word.Application();
wordDocuments = wordApp.Documents;
wordApp.Visible = false;
}
count = StatisticsWord(wordDocuments,file);
fileCount ;
}
else if (excel && excelExts.IndexOf(extName) > -1)
{
if (excelApp == null)
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
books = excelApp.Workbooks;
}
count = StatisticsExcel(books, file);
fileCount ;
}
else if (pdf && ".pdf".Equals(extName))
{
count = StatisticsPDF(file);
fileCount ;
}
if (count > -1)
{
pageCount = count;
}
RefreshStatus(file, filesToStatistics.Count, 1, string.Concat(progress, "/", filesToStatistics.Count));
//RefreshGridView();
if (!threadSignal_Do_Next)
break;
}
}
finally
{
if (wordDocuments != null)
{
//wordDocuments.Close();
Marshal.ReleaseComObject(wordDocuments);
wordDocuments = null;
}
if (wordApp != null)
{
wordApp.Quit();
Marshal.ReleaseComObject(wordApp);
wordApp = null;
}
if (books != null)
{
books.Close();
Marshal.ReleaseComObject(books);
books = null;
}
if (excelApp != null)
{
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
excelApp = null;
}
}
List<List<string>> rows = new List<List<string>>();
List<string> row = new List<string>(new string[] { "合计:", pageCount.ToString(), "" });
rows.Add(row);
AddDataIntoGrid(rows);
GC.Collect();
ChangeButtonState(btnDo,true);
ChangeButtonState(btnStop, false);
}
private int StatisticsPDF(string file)
{
string remark = "";
iTextSharp.text.pdf.PdfReader reader = null;
int count =0;
try
{
reader = new iTextSharp.text.pdf.PdfReader(file);
count = reader.NumberOfPages;
}
catch (Exception ex)
{
remark = "统计失败:" ex.Message;
}
List<List<string>> rows = new List<List<string>>();
List<string> row = new List<string>(new string[] { file, count.ToString(), remark });
rows.Add(row);
if (reader != null)
{
reader.Close();
reader.Dispose();
}
AddDataIntoGrid(rows);
return count;
}
private void RefreshGridView()
{
if (dataGridView1.InvokeRequired)
{
RefreshGridViewDelegate rgv = new FrmPagesStatistics.RefreshGridViewDelegate(RefreshGridView);
dataGridView1.Invoke(rgv);
}
else
{
dataGridView1.Update();
dataGridView1.Refresh();
}
}
private void RefreshStatus(string status,int maximum, int pbValue, string progress)
{
if (statusStrip1.InvokeRequired == false)
{
tsProgressBar.Maximum = maximum;
tsslStatus.Text = status;
tsProgressBar.Value = pbValue;
tsslPages.Text = progress;
}
else
{
RefreshStatusDelegate rs = new RefreshStatusDelegate(RefreshStatus);
this.statusStrip1.Invoke(rs, status,maximum, pbValue, progress);
}
}
private void ChangeButtonState(Button owner,bool state)
{
if (btnDo.InvokeRequired)
{
ChangeButtonStateDelegate cbs = new ChangeButtonStateDelegate(ChangeButtonState);
owner.Invoke(cbs,owner,state);
}
else
{
owner.Enabled = state;
}
}
//private int StatisticsExcel(string file)
//{
// Acey.ExcelX.IWorkbook book = Acey.ExcelX.ExcelxApplication.Open(file);
// int sheetPageCount = 0;
// Acey.ExcelX.IWorksheetCollection sheets = book.Worksheets;
// for (int i = 0; i < sheets.Count && threadSignal_Do_Next; i )
// {
// Acey.ExcelX.IWorksheet sheet = sheets[i];
// string sheetName = sheet.Name;
// Acey.ExcelX.IPageSetup pageSetup = sheet.PageSetup;
// Excel.Pages pages =pageSetup.Pages;
// sheetPageCount = pages.Count;
// }
//}
private int StatisticsExcel(Excel.Workbooks books, string item)
{
if (searchedFiles.IndexOf(item) > -1)
return 0;
int count = 0;
string remark = "";
Excel.Workbook book = null;
List<List<string>> rows = new List<List<string>>();
try
{
book = books.Open(item);
Excel.Sheets sheets = book.Sheets;
int sheetPageCount = 0;
for (int i = 0; i < sheets.Count && threadSignal_Do_Next; i )
{
object oSheet = sheets.get_Item(i 1);
Excel.Worksheet sheet = (Excel.Worksheet)oSheet;
Excel.Range range = sheet.UsedRange;
object value = range.Value;
Marshal.ReleaseComObject(range);
range = null;
if (value == null)
{
Marshal.ReleaseComObject(sheet);
sheet = null;
oSheet = null;
continue;
}
string sheetName = sheet.Name;
Excel.PageSetup pageSetup = sheet.PageSetup;
Excel.Pages pages = pageSetup.Pages;
sheetPageCount = pages.Count;
Marshal.ReleaseComObject(pages);
pages = null;
Marshal.ReleaseComObject(pageSetup);
pageSetup = null;
Marshal.ReleaseComObject(sheet);
sheet = null;
oSheet = null;
List<string> row = new List<string>(new string[] { " " sheetName, sheetPageCount.ToString(), "" });
rows.Add(row);
count = sheetPageCount;
}
Marshal.ReleaseComObject(sheets);
sheets = null;
}
catch (Exception ex)
{
remark = string.Concat("统计失败:", ex.Message);
}
finally
{
if (book != null)
{
try{
book.Close();
Marshal.ReleaseComObject(book);
book = null;
}
catch
{
}
}
}
GC.Collect();
List<string> topRow=new List<string>(new string[] {item, count.ToString(), remark });
rows.Insert(0, topRow);
AddDataIntoGrid(rows);
return count;
}
private static object obj = new object();
private void AddDataIntoGrid(List<List<string>> rows)
{
if (listView1.InvokeRequired)
{
AddDataIntoGridViewDelegate rgv = new FrmPagesStatistics.AddDataIntoGridViewDelegate(AddDataIntoGrid);
listView1.BeginInvoke(rgv, rows);
}
else
{
lock (obj)
{
// dataGridView1.DataSource = null;
//foreach (DataRow row in rows)
//{
// table.Rows.Add(row);
//}
//dataGridView1.DataSource = table;
//dataGridView1.Update();
//dataGridView1.Refresh();
foreach (List<string> row in rows)
{
ListViewItem item = new ListViewItem();
item.Text = (listView1.Items.Count 1).ToString();
table.Add(row);
item.SubItems.AddRange(row.ToArray());
listView1.Items.Add(item);
//listView1.Items.Add(new ListViewItem((string[])row.ItemArray));
}
}
}
}
private int StatisticsWordDocIO(string item)
{
if (searchedFiles.IndexOf(item) > -1)
return 0;
int count = 0;
string remark = "";
Syncfusion.DocIO.DLS.WordDocument wordDoc = new Syncfusion.DocIO.DLS.WordDocument();
try
{
wordDoc.OpenReadOnly(item, FormatType.Automatic);
count = wordDoc.BuiltinDocumentProperties.PageCount;
}
catch (Exception ex)
{
remark = string.Concat("统计失败:", ex.Message);
}
finally
{
wordDoc.Close();
}
List<List<string>> rows = new List<List<string>>();
List<string> row =new List<string>(new string[] {item, count.ToString(), remark });
rows.Add(row);
AddDataIntoGrid(rows);
return count;
}
private int StatisticsWord(Word.Documents wordDocuments, string item)
{
if (searchedFiles.IndexOf(item) > -1)
return 0;
int count = 0;
string remark = "";
object oFileName = item;
Word.Document wordDoc = null;
object oMissing = Type.Missing;
object oTrue=true;
object oFalse = false;
try
{
wordDoc = wordDocuments.Open(ref oFileName,ref oFalse,ref oTrue,ref oFalse
, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oFalse);
Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
count = wordDoc.ComputeStatistics(stat, ref oMissing);
//object oDocProps = wordDoc.BuiltInDocumentProperties;
//Type typeDocBuiltInProps = oDocProps.GetType();
//string strIndex = "Number of Pages";
//string strValue;
//object docProp = typeDocBuiltInProps.InvokeMember("Item",
// BindingFlags.Default |
// BindingFlags.GetProperty,
// null, oDocProps,
// new object[] { strIndex });
//Type typeDocPageProp = docProp.GetType();
//strValue = typeDocPageProp.InvokeMember("Value",
// BindingFlags.Default |
// BindingFlags.GetProperty,
// null, docProp,
// new object[] { }).ToString();
//count = int.Parse(strValue);
//Marshal.ReleaseComObject(docProp);
//docProp = null;
//Marshal.ReleaseComObject(oDocProps);
////docProps = null;
//oDocProps = null;
}
catch (Exception ex)
{
remark = string.Concat("统计失败:", ex.Message);
}
finally
{
if (wordDoc != null)
{
try
{
wordDoc.Close(ref oFalse);
Marshal.ReleaseComObject(wordDoc);
wordDoc = null;
}
catch
{
}
}
}
List<List<string>> rows = new List<List<string>>();
rows.Add(new List<string>(new string[] { item, count.ToString(), remark }));
AddDataIntoGrid(rows);
return count;
}
private void btnExport_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Excel 文件(*.xls)|*.xls|所有文件(*.*)|*.*";
dlg.CheckPathExists = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
ExportResult(dlg.FileName);
}
}
private void ExportResult(string fileName)
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
}
catch (Exception ex)
{
Common.ErrDlg(this, "无法覆盖存在的文件:\r\n" ex.Message);
return;
}
}
Syncfusion.XlsIO.ExcelEngine engine = new ExcelEngine();
IWorkbook book = engine.Excel.Workbooks.Add();
try
{
DataTable data = new DataTable();
data.Columns.Add("序号", typeof(int));
data.Columns.Add("文件", typeof(string));
data.Columns.Add("页数", typeof(int));
data.Columns.Add("备注", typeof(string));
for (int i = 0; i < table.Count; i )
{
List<string> dataRow = table[i];
DataRow row = data.NewRow();
row.ItemArray = new object[] { i, dataRow[0], Convert.ToInt32(dataRow[1]), dataRow[2] };//()...LastIndexOf each(List<string>
data.Rows.Add(row);
}
book.ActiveSheet.ImportDataTable(data, true, 1, 1);
book.SaveAs(fileName);
book.Close();
engine.Dispose();
if (File.Exists(fileName))
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
psi.Arguments = "/e,/select," fileName;
System.Diagnostics.Process.Start(psi);
}
}
catch (Exception ex)
{
Common.ErrDlg(this, "导出失败:\r\n" ex.Message);
}
finally
{
book.Close();
engine.Dispose();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
threadSignal_Do_Next = false;
btnStop.Enabled = false;
}
private void listView1_Resize(object sender, EventArgs e)
{
ArrangeGrid();
}
private void ArrangeGrid()
{
listView1.Columns[1].Width = listView1.ClientSize.Width - 220;
}
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论