当前位置:网站首页>Project summary: document management system
Project summary: document management system
2022-07-21 16:09:00 【I Can -Jiang】
This article mainly combs and summarizes the project of document management system :
System language localization
Because the system requires Bilingual , A form parameter is used in the design :
After setting these two parameters , You can see two resource files in the solution , One is the design language , One is localized .
You can modify the display name of the control in the resource file .
When the system is running, it will be localized according to its own local language . But this is not very convenient to use , If the system localization is set , That is, after changing the values of the above two parameters, you can no longer add controls , If you need to add controls, restore these two parameters to the default , Then add controls , You also need to reset the name of the control in the localized resource file .
Moreover, this method can only localize the controls added at the front end , If it's written directly in the background , such as GridControl Column name of ,Messagebox The news of , Cannot localize settings , This makes the system seem inconsistent .
Form animation
Take a look at the display effect , Bad intercept map , Set here to display... From the upper left corner .
But if it's set MID Form embedding Panel It won't work if
#region AnimateWindow
[DllImport("user32.dll", EntryPoint = "AnimateWindow")]
private static extern bool AnimateWindow(IntPtr handle, int ms, int flags);
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//AnimateWindow(this.Handle, 1000, 0x20010); // Center and gradually show .
AnimateWindow(this.Handle, 1000, 0xA0000); // Fade in / out effect .
//AnimateWindow(this.Handle, 1000, 0x60004); // From top to bottom .
//AnimateWindow(this.Handle, 1000, 0x20004); // From top to bottom .
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
//AnimateWindow(this.Handle, 1000, 0x10010); // Center and gradually hide .
AnimateWindow(this.Handle, 1000, 0x90000); // Fade in / out effect .
//AnimateWindow(this.Handle, 1000, 0x50008); // Bottom up .
//AnimateWindow(this.Handle, 1000, 0x10008); // Bottom up .
}
#endregion
One is the form display , One is when you close the form , But this animation effect is not many , Then the effect of fading in and out is very similar to Caton's , The original purpose of using animation effect is to enhance the user experience , Solve the problem of flashing screen for form construction and switching , But it's not very easy to use , This function , When switching between two forms, only one form can be animated , Otherwise, the two animations seem particularly deliberate .
During this period, we also found a solution to the problem of flashing screen when switching forms , But it's not easy to use , Combined with form animation, it's like a card screen .
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000;
return cp;
}
}
TileControl
One customer, one group , Customers occupy two spaces , Items occupy one space .
The background automatically instantiates groups and projects according to the database :
public void Group()
{
CustomerTile.Groups.Clear();
sql = "select ID,CustomerName from Customer ";
DataTable dt;
if (!DB.AF.execSql(sql, sqlconn, out dt))
{
XtraMessageBox.Show(" Failed to get server client !");
return;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
TileGroup group = new TileGroup();
group.Text = dt.Rows[i]["ID"].ToString();
CustomerTile.Groups.Add(group);
TileItem item = new TileItem();
item.Name = dt.Rows[i]["CustomerName"].ToString();
item.Text = dt.Rows[i]["CustomerName"].ToString();
item.ItemSize = TileItemSize.Wide;// Set group header first Item Two spaces
// Built in some pictures of customers . When adding customers Item These pictures will be displayed , If it's not built in , It's green tiles .
switch (item.Name)
{
case "Apple": item.Image = Resources.Apple; break;
case "Amazon": item.Image = Resources.Amazon; break;
case "Facebook": item.Image = Resources.Facebook; break;
case "Google": item.Image = Resources.Google; break;
case "Huawei": item.Image = Resources.Huawei; break;
case "Microsoft": item.Image = Resources.Microsoft; break;
}
item.ImageScaleMode = TileItemImageScaleMode.Stretch;
item.Appearance.BackColor = Color.White;// The background color of the ceramic tile is set here , Otherwise there will be a border , I didn't find out how to fill the picture completely .
item.Appearance.ForeColor = Color.Black;
// Tile click event , Customer and project click events are different , This is the customer's click event , Here is the of the project
item.ItemClick += Item_Click;
group.Items.Add(item);
// You can add one here top, because Item Too many will be on the right , Disgraceful
sql = "select ID,ProjectName from Projects where CusName= '" + dt.Rows[i]["CustomerName"].ToString() + "'";
DataTable dtPro;
if (!DB.AF.execSql(sql, sqlconn, out dtPro))
{
XtraMessageBox.Show(" Failed to get server project !");
}
for (int j = 0; j < dtPro.Rows.Count; j++)
{
TileItem items = new TileItem();
items = new TileItem();
items.Name = dtPro.Rows[j]["ID"].ToString();
items.Text = dtPro.Rows[j]["ProjectName"].ToString();
items.ItemSize = TileItemSize.Default;
// Here is the click event of the project
items.ItemClick += Items_Click;
group.Items.Add(items);
}
}
}
TileControl Still often do touch screen interface ,Win8 Style , The project's Item Change pictures into folders , It's also nice to put the text in the middle at the bottom , This control is still very easy to use , There are too few information available on the Internet .
Rowcount Is to change a column to show several rows Item Of .
TreeList and BreadCrumbEdit
Dev It doesn't do TreeList and BreadCrumbEdit The associated , So I can only write it myself , An example is given on the official website , I have a general look , I'll add this later .
Upload files
There are two ways to upload files :
- Get the path of the file from the clipboard , Directly upload when pasting in the program
- Click the upload button , A dialog box for selecting files pops up . Select and upload
About version management : Making a file management system not only needs to be convenient 、 quick 、 It works 、 Share the current version of files safely , It is more necessary to manage the historical versions uploaded by users , At present, all I think of is storage , It's not in the management stage yet .
This file management system saves files by uploading them to a shared folder , Not to binary, stored in the database .
Therefore, the method of version management is to create two folders in the shared server , A file used to store the current version , Used to share 、 preview , In another folder, create your own folder according to the name of each file , Every time you upload a file , The file name is + Save the version number .
If a file with the same name already exists in the shared folder, it will be directly overwritten if you continue to upload , Therefore, no other operations are required for the folder storing the current version , If the name of the uploaded file is the same as that of the previous version , Just upgrade directly , However, the version to be upgraded may be inconsistent with the name of the file on the shared server , So I made a separate interface :
First put a general code for operating shared folders , These functions will be used later :
#region Shared folders
public static bool connectState(string path)
{
return connectState(path, "", "");
}
/// <summary>
/// Connect to a remote shared folder
/// </summary>
/// <param name="path"> The path to the remote shared folder </param>
/// <param name="userName"> user name </param>
/// <param name="passWord"> password </param>
/// <returns></returns>
public static bool connectState(string path, string userName, string passWord)
{
bool Flag = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.StandardInput.WriteLine("net use * /del /y");
string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
MessageBox.Show(errormsg);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
/// <summary>
/// Save local content to a remote folder , Or download files from remote folders to local
/// </summary>
/// <param name="src"> The path of the file to save , If you save files to a shared folder , This path is the local file path :@"D:\1.avi"</param>
/// <param name="dst"> Path to save file , No name and extension </param>
/// <param name="fileName"> Save the name and extension of the file </param>
public static void Transport(string src, string dst, string fileName)
{
FileStream inFileStream = new FileStream(src, FileMode.Open);
if (!Directory.Exists(dst))
{
Directory.CreateDirectory(dst);
}
dst = dst + fileName;
if (!File.Exists(dst))
{
FileStream outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write);
byte[] buf = new byte[inFileStream.Length];
int byteCount;
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
inFileStream.Flush();
inFileStream.Close();
outFileStream.Flush();
outFileStream.Close();
}
else if (File.Exists(dst))
{
File.Delete(dst);
FileStream outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write);
byte[] buf = new byte[inFileStream.Length];
int byteCount;
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
inFileStream.Flush();
inFileStream.Close();
outFileStream.Flush();
outFileStream.Close();
}
}
/// <summary>
/// Download files from remote server to local
/// </summary>
/// <param name="src"> The file path after downloading to the local , Contains the extension of the file </param>
/// <param name="dst"> Remote server path ( Shared folder path )</param>
/// <param name="fileName"> remote server ( Shared folders ) File name in , Include extension </param>
public static void TransportRemoteToLocal(string src, string dst, string fileName) //src: The file path after downloading to the local dst: Remote server path fileName: remote server dst File name under path
{
if (!Directory.Exists(Path.GetDirectoryName(src) + @"\")) { Directory.CreateDirectory(Path.GetDirectoryName(src) + @"\");
}
dst = dst + fileName;
FileStream inFileStream = new FileStream(dst, FileMode.Open); // Remote server files It is assumed that this file is indeed contained in the shared folder of the remote server , Otherwise, the program reports an error
FileStream outFileStream = new FileStream(src, FileMode.OpenOrCreate); // File downloaded from remote server to local
byte[] buf = new byte[inFileStream.Length];
int byteCount;
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
inFileStream.Flush();
inFileStream.Close();
outFileStream.Flush();
outFileStream.Close();
}
#endregion
Get the code of the clipboard file path :
if (Clipboard.ContainsFileDropList())
{
// Here is a page waiting for the form
WaitDialogForm sdf = new WaitDialogForm("", " Uploading data ......");
GC.Enabled = false;
try
{
//file Is the file path on the clipboard
foreach (string file in Clipboard.GetFileDropList())
{
// A method of uploading files written by yourself
upLoad(file);
}
}
catch (Exception ex)
{
XtraMessageBox.Show("Error : " + ex.Message);
}
finally
{
sdf.Close();
GC.Enabled = true;
}
}
How to upload files , First insert data into the database , Then save the file to a shared folder
public void upLoad(string file)
{
//string file = Clipboard.GetFileDropList()[0]; // Read the first file on the clipboard
FileInfo fileInfo = null;
try
{
fileInfo = new System.IO.FileInfo(file);
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
// Other exception handling code
}
System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(file);
string FileName = file.Substring(file.LastIndexOf("\\") + 1);
string FileType = file.Substring(file.LastIndexOf(".") + 1);
DataRowView drv = FileTree.GetDataRecordByNode(FileTree.FocusedNode) as DataRowView;
FousedeptId = drv["ID"].ToString();
sql = "select FileURL from Folder where ID = '" + FousedeptId + "'";
DataTable dt;
if (!DB.AF.execSql(sql, sqlconn, out dt))
{
XtraMessageBox.Show(" Failed to access database !");
return;
}
string url = dt.Rows[0][0].ToString() + @"\"; // Save the database first and then the server . sql = "insert into Folder(ProID,CusName,FileName,FileType,FileURL,UpID,FileSize) values('" + ProID + "','" + CusName + "','" + FileName + "','" + FileType + " file ','" + url + FileName + "','" + FousedeptId + "','" + System.Math.Ceiling(fileInfo.Length / 1024.0) + " KB" + "')";
if (!DB.AF.sqlExec(sql, sqlconn, out errMsg))
{
XtraMessageBox.Show(errMsg);
return;
}
bool status = false;
// Connect shared folders
status = connectState(@"\\ip\Project\ERP", " account number ", " password ");
if (status)
{
// Execution method , The above shared folder operation method
Transport(file, url, FileName);
}
//SetGV();
}
File preview
I checked a lot of information about document preview , But at present, there is no particularly good solution .Oracle There is a software that can preview hundreds of files , Can be embedded into C# in , Use as a control , be called AutoVue, But I don't feel so easy to use , The first is the long loading time , And it's previewing Excel When uploading files Excel There is no optimal column width ,AutoVue The display is incomplete , Zoom in and out is not very flexible , So I didn't continue to use it .
Another preview method is to call the process directly , Open the file by calling the program opened by default for this file type in the computer , However, it is not easy to determine the confidentiality of documents in this way , Because after opening, it is no longer within the controllable range of the program , Only other encryption software can be used to control the files .
System.Diagnostics.Process.Start(Localpath)//Localpath The address of the file to be previewed
File transfer XPS With the help of WPF preview
This txt、pdf、word The file needs to write a form ,excel Need to write a form .
pdf turn xps You need to turn first word, And then go xps, It takes a long time , Therefore, the cache for seven days is set xps file , When previewing again, you can directly call :
The front desk :
<dx:ThemedWindow
x:Class="Knowledge_Central.Views.XPSPreview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
Title="XPSPreview" Height="800" Width="1000" WindowState="Maximized"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0" Name="cdTree"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<GroupBox Header=" Navigation directory ">
<TreeView Name="tvTree" SelectedItemChanged="tvTree_SelectedItemChanged"/>
</GroupBox>
<GridSplitter Width="3" ResizeBehavior="PreviousAndNext" Grid.Column="1" Background="LightGray"/>
<Grid Grid.Column="3">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DocumentViewer Name="dvShow" Grid.Row="1" Background="#FFF0F0F0" />
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Right">
<CheckBox Content=" Show navigation " Margin="5,1,5,1.6" Name="cbNav" Width="75" Click="cbNav_Click" />
<Label Content=" page " Margin="0,2,0,-2.2"/>
<Label Name="lblCurPage" Margin="0"/>
<Label Name="lblPage"/>
<Button Content=" The previous page " Height="23" Name="btnPrev" Width="75" Click="btnPrev_Click" />
<Button Content=" The next page " Height="23" Name="btnNext" Width="75" Click="btnNext_Click" />
<!--<Label Content=" Total words :" Name="lblWordCount"/>-->
</StackPanel>
</Grid>
</Grid>
</dx:ThemedWindow>
backstage :
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Xps.Packaging;
using System.Xml;
using Microsoft.Office.Interop.Word;
using DevExpress.Xpf.Core;
using DevExpress.XtraEditors;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Knowledge_Central.Views
{
/// <summary>
/// MainWindow.xaml Interaction logic of
/// </summary>
public partial class XPSPreview : ThemedWindow
{
string name;
#region Global variables
/// <summary>
/// Used to store all nodes of the directory document OutlineLevel value , And into int type
/// </summary>
int[] array = null;
/// <summary>
/// Used to store all nodes of the directory document OutlineLevel value
/// </summary>
string[] array1 = null;
/// <summary>
/// Used to store all nodes of the directory document Description value , Chapter information
/// </summary>
string[] arrayName = null;
/// <summary>
/// Used to store all nodes of the directory document OutlineTarget value , Page information
/// </summary>
string[] pages = null;
#endregion
public XPSPreview()
{
InitializeComponent();
}
/// <summary>
/// Constructors
/// </summary>
/// <param name="strFilePath"> File path </param>
public XPSPreview(string strFilePath) : this() {
OpenFile(strFilePath); }
#region Method
/// <summary>
/// Read the navigation directory
/// </summary>
private void ReadDoc(XpsDocument xpsDoc)
{
IXpsFixedDocumentSequenceReader docSeq = xpsDoc.FixedDocumentSequenceReader;
IXpsFixedDocumentReader docReader = docSeq.FixedDocuments[0];
XpsStructure xpsStructure = docReader.DocumentStructure;
Stream stream = xpsStructure.GetStream();
XmlDocument doc = new XmlDocument();
doc.Load(stream);
// Get the list of nodes
XmlNodeList nodeList = doc.ChildNodes.Item(0).FirstChild.FirstChild.ChildNodes;
if (nodeList.Count <= 0)// Determine whether there is a directory node
{
//tvTree.Visibility = System.Windows.Visibility.Hidden;
tvTree.Items.Add(new TreeViewItem {
Header = " No navigation directory " });
return;
}
tvTree.Visibility = System.Windows.Visibility.Visible;
array = new int[nodeList.Count];
array1 = new string[nodeList.Count];
arrayName = new string[nodeList.Count];
pages = new string[nodeList.Count];
for (int i = 0; i < nodeList.Count; i++)
{
array[i] = Convert.ToInt32(nodeList[i].Attributes["OutlineLevel"].Value);
array1[i] = nodeList[i].Attributes["OutlineLevel"].Value.ToString();
arrayName[i] = nodeList[i].Attributes["Description"].Value.ToString();
pages[i] = nodeList[i].Attributes["OutlineTarget"].Value.ToString();
}
for (int i = 0; i < array.Length - 1; i++)
{
// Yes array Transform and assemble into a readable tree structure , adopt ASCII Value 、 transformation
array1[0] = "A";
if (array[i + 1] - array[i] == 1)
{
array1[i + 1] = array1[i] + 'A';
}
if (array[i + 1] == array[i])
{
char s = Convert.ToChar(array1[i].Substring((array1[i].Length - 1), 1));
array1[i + 1] = array1[i].Substring(0, array1[i].Length - 1) + (char)(s + 1);
}
if (array[i + 1] < array[i])
{
int m = array[i + 1];
char s = Convert.ToChar(array1[i].Substring(0, m).Substring(m - 1, 1));
array1[i + 1] = array1[i].Substring(0, m - 1) + (char)(s + 1);
}
}
// Add a node as the root node
TreeViewItem parent = new TreeViewItem();
TreeViewItem parent1 = null;
parent.Header = " Directory navigation ";
Boolean flag = false;
for (int i = 0; i < array.Length; i++)
{
if (array[i] == 1)
{
flag = true;
}
if (flag) // If the actual root node is found , Load tree
{
parent1 = new TreeViewItem();
parent1.Header = arrayName[i];
parent1.Tag = array1[i];
parent.Items.Add(parent1);
parent.IsExpanded = true;
parent1.IsExpanded = true;
FillTree(parent1, array1, arrayName);
flag = false;
}
}
tvTree.Items.Clear();
tvTree.Items.Add(parent);
}
/// <summary>
/// How to fill the tree
/// </summary>
/// <param name="parentItem"></param>
/// <param name="str1"></param>
/// <param name="str2"></param>
public void FillTree(TreeViewItem parentItem, string[] str1, string[] str2)
{
string parentID = parentItem.Tag as string;
for (int i = 0; i < str1.Length; i++)
{
if (str1[i].IndexOf(parentID) == 0 && str1[i].Length == (parentID.Length + 1) && str1[i].ElementAt(0).Equals(parentID.ElementAt(0)))
{
TreeViewItem childItem = new TreeViewItem();
childItem.Header = str2[i];
childItem.Tag = str1[i];
parentItem.Items.Add(childItem);
FillTree(childItem, str1, str2);
}
}
}
/// <summary>
/// Open file - If the incoming path is empty, the select file dialog box opens here
/// </summary>
/// <param name="strFilepath"> The full path of the incoming file </param>
private void OpenFile(string strFilepath)
{
if (string.IsNullOrEmpty(strFilepath))
{
//Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.DefaultExt = ".doc|.txt|.xps";
//openFileDialog.Filter = "*(.xps)|*.xps|Word documents (.doc)|*.doc|Word(2007-2010)(.docx)|*.docx|*(.txt)|*.txt";
//Nullable<bool> result = openFileDialog.ShowDialog();
//strFilepath = openFileDialog.FileName;
//if (result != true)
//{
return;
//}
}
this.Title = strFilepath.Substring(strFilepath.LastIndexOf("\\") + 1);
if (strFilepath.Length > 0)
{
string newXPSdocName = string.Concat(Path.GetDirectoryName(strFilepath), "\\", Path.GetFileNameWithoutExtension(strFilepath), ".xps");
XpsDocument xpsDoc = null;
// If it is xps Open the file directly , Otherwise, the format needs to be converted
if (!strFilepath.EndsWith(".xps"))
{
string FileType = strFilepath.Substring(strFilepath.LastIndexOf(".") + 1);
switch (FileType)
{
case "pdf":
case "doc":
case "docx":
case "txt":
{
xpsDoc = ConvertWordToXPS(strFilepath, newXPSdocName);
}; break;
case "xls":
case "xlsx":
{
xpsDoc = ConvertExcelToXps(strFilepath, newXPSdocName); }
; break;
}
File.Delete(strFilepath);
}
else
{
xpsDoc = new XpsDocument(strFilepath, System.IO.FileAccess.Read);
}
//}
if (xpsDoc != null)
{
dvShow.Document = xpsDoc.GetFixedDocumentSequence();
// Read the document directory
ReadDoc(xpsDoc);
xpsDoc.Close();
}
this.lblCurPage.Content = 1;
this.lblPage.Content = "/" + dvShow.PageCount;
}
}
/// <summary>
/// take word Document conversion to xps file
/// </summary>
/// <param name="wordDocName">word Document full path </param>
/// <param name="xpsDocName">xps Document full path </param>
/// <returns></returns>
private XpsDocument ConvertWordToXPS(string wordDocName, string xpsDocName)
{
XpsDocument result = null;
// Create a word file , And add the document to be converted to the newly created object
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
try
{
wordApplication.Documents.Add(wordDocName);
Document doc = wordApplication.ActiveDocument;
doc.ExportAsFixedFormat(xpsDocName, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, true, true, false, Type.Missing);
result = new XpsDocument(xpsDocName, System.IO.FileAccess.ReadWrite);
}
catch (Exception ex)
{
string error = ex.Message;
wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);
}
wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);
return result;
}
/// <summary>
/// take Excel The file is converted to XPS file
/// </summary>
/// <param name="execelFileName">Excel file name </param>
/// <param name="xpsFileName"> The conversion xps file name </param>
public XpsDocument ConvertExcelToXps(string excelFileName, string xpsFileName)
{
XpsDocument result = null;
if (string.IsNullOrWhiteSpace(excelFileName))
throw new ArgumentNullException(excelFileName);
var fileInfo = new FileInfo(xpsFileName);
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.DisplayAlerts = false;
Workbooks wbs;
Workbook wb;
wbs = app.Workbooks;
wb = wbs.Add(excelFileName);
dynamic Nothing = System.Reflection.Missing.Value;
wb.ExportAsFixedFormat(XlFixedFormatType.xlTypeXPS, xpsFileName, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
result = new XpsDocument(xpsFileName, System.IO.FileAccess.ReadWrite);
wb.Close(true);
wbs.Close();
app.Quit();
KillExcelProcess(app);
return result;
}
[DllImport("User32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);
/// <summary>
/// end Excel process
/// </summary>
/// <param name="obj"></param>
private void KillExcelProcess(Microsoft.Office.Interop.Excel.Application app)
{
if (app == null)
return;
try
{
IntPtr intptr = new IntPtr(app.Hwnd);
int id;
GetWindowThreadProcessId(intptr, out id);
var p = Process.GetProcessById(id);
p.Kill();
}
catch {
}
}
#endregion
/// <summary>
/// Navigation tree jump event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
int x = 0;
TreeViewItem selectTV = this.tvTree.SelectedItem as TreeViewItem;
if (null == selectTV)
return;
if (null == selectTV.Tag)
return;
string page = selectTV.Tag.ToString();
for (int i = 0; i < array1.Length; i++)
{
if (array1[i].Equals(page))
{
x = i;
}
}
string[] strPages = pages[x].Split('_');
dvShow.GoToPage(Int32.Parse(strPages[1]));
}
private void cbNav_Click(object sender, RoutedEventArgs e)
{
this.cdTree.Width = this.cbNav.IsChecked == true ? new GridLength(300) : new GridLength(0);
}
private void btnPrev_Click(object sender, RoutedEventArgs e)
{
this.dvShow.PreviousPage();
if (int.Parse(this.lblCurPage.Content.ToString()) > 1)
this.lblCurPage.Content = int.Parse(this.lblCurPage.Content.ToString()) - 1;
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
this.dvShow.NextPage();
if (int.Parse(this.lblCurPage.Content.ToString()) < int.Parse(this.lblPage.Content.ToString().Replace("/", "")))
this.lblCurPage.Content = int.Parse(this.lblCurPage.Content.ToString()) + 1;
}
}
}
Excel preview :Excel It can also be converted to xps File preview , But I didn't turn around , But with the SpreadsheetControl This control , In fact, it can be used without turning winform and wpf It's all the same , This control is used to display excel file .
<dx:ThemedWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
xmlns:dxsps="http://schemas.devexpress.com/winfx/2008/xaml/spreadsheet"
x:Class="Knowledge_Central.Views.XPSPreview_Excel"
Title="XPSPreview_Excel" Height="800" Width="1000" WindowState="Maximized"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<dxsps:SpreadsheetFormulaBarControl x:Name="formulaBar" SpreadsheetControl="{Binding ElementName=spreadsheetControl1}" />
<dxsps:SpreadsheetControl Grid.Row="1" x:Name="spreadsheetControl1"/>
</Grid>
</dx:ThemedWindow>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DevExpress.Xpf.Core;
using DevExpress.Spreadsheet;
namespace Knowledge_Central.Views
{
/// <summary>
/// Interaction logic for XPSPreview_Excel.xaml
/// </summary>
public partial class XPSPreview_Excel : ThemedWindow
{
public XPSPreview_Excel(string path)
{
InitializeComponent();
PreviewExcel(path);
}
public void PreviewExcel(string filePath)
{
IWorkbook workbook = spreadsheetControl1.Document;
workbook.LoadDocument(filePath);
}
}
}
File download
Downloading and saving files locally is the easiest
WaitDialogForm sdf = new WaitDialogForm("", " Downloading files , One moment please ......");
GC.Enabled = false;
string name = GV.GetRowCellValue(GV.FocusedRowHandle, "Name").ToString();
string path = GV.GetRowCellValue(GV.FocusedRowHandle, "URL").ToString();
string Localpath = @"D:\KnowledgeCentralFiles\" + name; if (File.Exists(path)) { try { bool status = false; // Connect shared folders status = connectState(@"\\ip\Project\ERP", " Account ", " password ");
if (status)
{
TransportRemoteToLocal(Localpath, Path.GetDirectoryName(GV.GetRowCellValue(GV.FocusedRowHandle, "URL").ToString()) + @"\", name); } } catch (Exception ex) { XtraMessageBox.Show(ex.Message); return; } } sdf.Close(); GC.Enabled = true; if (XtraMessageBox.Show(" Download successful , Whether to open now ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
System.Diagnostics.Process.Start(Localpath);
}
Rights management
Permission management is an important module of this system . There are three dimensions : Permission group , Personnel authority , File permissions
- Permission group
Whether to display the detailed personnel of the permission group during the general query of the permission group , Because you have to change the number of columns , So to reset GridView, Used two sentences of grammar :
Both the above sentence and the following sentence can be used
//(GC.DefaultView as GridView).Columns.Clear();// You need to clear the column before switching .
GC.DataSource = dt;
(GC.DefaultView as GridView).PopulateColumns();
Add permission group :
The new version of the DevExpress Of GridControl It has its own paste function , At present, it seems to be divided into update and addition , If you want to update and append , Maybe you should write it yourself .
Here, the additional... Is used directly , Because only the job number column needs to be maintained , The name is automatically brought out , It doesn't need to be updated :
In addition, I used GridLookUpEdit Column and fuzzy query function :
When submitting the work number column value , Automatically assign a value to the name column , I wonder if there is a simpler way , Actually, I visited the database twice .
private void GV_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
//XtraMessageBox.Show(e.Column.ToString());
if (e.Column.ToString().Trim() == " Job number ")
{
sql = "select userName full name from sys_userInf where userID = '" + GV.GetRowCellValue(GV.FocusedRowHandle, " Job number ").ToString().Trim() + "'";
DataTable dt;
if (!DB.AF.execSql(sql, sqlconnOA, out dt))
{
XtraMessageBox.Show(" Failed to connect to personnel information server !");
return;
}
if (dt.Rows.Count == 1)
{
GV.SetRowCellValue(GV.FocusedRowHandle, " full name ", dt.Rows[0][0].ToString());
// GV.SetRowCellValue(GV.FocusedRowHandle, " Code ", txt_Code.Text.Trim());
}
}
}
GridLookUpEdit Column and fuzzy query :
public void Initcol()
{
sql = "select userID Job number ,userName full name ,deptName department ,companyName company from sys_userInf";
DataTable dt;
if (!DB.AF.execSql(sql, sqlconnOA, out dt))
{
XtraMessageBox.Show(" Failed to connect to personnel information server !");
}
RepositoryItemGridLookUpEdit rc = new RepositoryItemGridLookUpEdit(); // This line is the key
rc.DataSource = new BindingSource(dt, null);
rc.ValueMember = " Job number ";
rc.DisplayMember = " Job number ";
rc.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
rc.View.BestFitColumns();
rc.NullText = "";
rc.ShowFooter = false;
rc.View.OptionsView.ShowAutoFilterRow = false; // Show not show grid The first blank line on the , It is also an application for Retrieval
rc.AutoComplete = false;
rc.ImmediatePopup = true;
rc.PopupFilterMode = PopupFilterMode.Contains;
rc.TextEditStyle = TextEditStyles.Standard;
SetGridLookUpEditMoreColumnFilter(rc);
GC.RepositoryItems.Add(rc);// This business is also the key
GV.Columns[" Job number "].ColumnEdit = rc;// This business is also the key
//if (string.IsNullOrEmpty(rc.View.GetFocusedDataRow()[" full name "].ToString()))
// GV.SetRowCellValue(GV.FocusedRowHandle, " full name ", rc.View.GetFocusedDataRow()[" full name "].ToString());
}
/// <summary>
/// GridLookupEdit Fuzzy query
/// </summary>
/// <param name="repGLUEdit"></param>
private void SetGridLookUpEditMoreColumnFilter(RepositoryItemGridLookUpEdit repGLUEdit)
{
repGLUEdit.EditValueChanging += (sender, e) =>
{
BeginInvoke(new MethodInvoker(() =>
{
GridLookUpEdit edit = sender as GridLookUpEdit;
DevExpress.XtraGrid.Views.Grid.GridView view = edit.Properties.View as DevExpress.XtraGrid.Views.Grid.GridView;
// obtain GriView Private variables
System.Reflection.FieldInfo extraFilter = view.GetType().GetField("extraFilter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
List<DevExpress.Data.Filtering.CriteriaOperator> columnsOperators = new List<DevExpress.Data.Filtering.CriteriaOperator>();
foreach (GridColumn col in view.VisibleColumns)
{
if (col.Visible && col.ColumnType == typeof(string))
columnsOperators.Add(new DevExpress.Data.Filtering.FunctionOperator(DevExpress.Data.Filtering.FunctionOperatorType.Contains,
new DevExpress.Data.Filtering.OperandProperty(col.FieldName),
new DevExpress.Data.Filtering.OperandValue(edit.Text)));
}
string filterCondition = new DevExpress.Data.Filtering.GroupOperator(DevExpress.Data.Filtering.GroupOperatorType.Or, columnsOperators).ToString();
extraFilter.SetValue(view, filterCondition);
// obtain GriView A private method that handles column filtering in
System.Reflection.MethodInfo ApplyColumnsFilterEx = view.GetType().GetMethod("ApplyColumnsFilterEx", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
ApplyColumnsFilterEx.Invoke(view, null);
}));
};
}
After the group is built , Then set permissions for the group :
The permissions here are for folders , preview 、 Upload 、 An updated version 、 download 、 Delete
- Personnel authority
Personnel permissions are relatively simple - File permissions
File permissions are not ready yet , Do a good job and then update
边栏推荐
- 获取当前 标注样式dimstyle
- 【Flutter -- 实战】快速入门 Flutter
- [JS] event communication
- 小程序毕设作品之微信疫苗预约小程序毕业设计(8)毕业设计论文模板
- 深度解析:链动2+1模式是如何玩转招商引流的
- What aspects should we start from to learn the silver K-line chart
- 小程序毕设作品之微信疫苗预约小程序毕业设计(7)中期检查报告
- Training of head and neck segmentation networks with shape prior on small datasets
- TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation
- Blueprism tool menu bar user rights function description -rpa Chapter 2
猜你喜欢
EasyGBS平台设置小技巧:如何隐藏平台web页面不被访问?
[mqtt from introduction to improvement series | 08] mqtt3.1.1 topic details
Wechat vaccine appointment applet graduation project of applet completion work (6) opening defense ppt
[Yugong series] go teaching course in July 2022 014 arithmetic operators of operators
小程序毕设作品之微信疫苗预约小程序毕业设计(7)中期检查报告
Algorithm summary] 20 questions to complete bat interview - binary tree
数据库约束&&MySQL进阶查询
C | array and pointer
Why is sha256 irreversible and how secure is sha256
原码、补码以及定点数运算
随机推荐
[shutter -- actual combat] quick start shutter
Using go TCP to realize simple online group chat function
c || 文件操作
How to make localstorage support expiration time setting?
Algorithm summary] 20 questions to complete bat interview - binary tree
Because mongodb didn't get started, I lost an internship
小程序毕设作品之微信疫苗预约小程序毕业设计(1)开发概要
BluePrism工具菜单栏用户权限功能描述-RPA第二章
2022/07/20 learning notes (Day12) string string string
小程序毕设作品之微信疫苗预约小程序毕业设计(7)中期检查报告
【Flutter -- 实战】快速入门 Flutter
conda虚拟环境默认路径如何修改
【STC15控制WS2812 RGB彩灯级联】
TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation
Flask's operations on model classes
传统零售企业如何促进消费循环、分享购模式赋能实体企业发展?
手机股票开户有没有风险的?安全靠谱吗?
c || 数组与指针
-实体建模-
Word report reference format