在系统使用一段时间可能由于某些原因需要将以前的数据和文件备份到文件
描述:将DB中的多个table 数据备份到Excel文件并打包压缩为zip,将需要备份的文件打包压缩Zip后删除文件
下面是使用DocumentFormat.OpenXml 和Microsoft.Practices的一个帮助类,Copy代码可以直接使用
需要引进如下图dll
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace databackupandfilebackup
{
public class CommonFunctions
{
#region Data backup
///
/// 将dataset的数据集备份到EXCEL文件 每个table为一个文件,最后将所有导出的excel文件压缩到zip文件里
///
/// 数据集
/// 文件备份路径
public static void HousekeepDataBackUp(DataSet dataset,string houseKeepingFilePath)
{
try
{
string HouseKeepingFilePath = houseKeepingFilePath;
//Get data
DataSet ds = dataset;
int tablescount = ds.Tables.Count;
//注意构造此Dataset时
//此处Dataset中的最后一个table中存储的是前面tables的表名称
// ds = SqlHelper.ExecuteDataSet("[SRC].[USP_Housekeeping_GetAllData]", null);
string[] datanames = new string[ds.Tables.Count - 1];
string[] dataFileNames = new string[ds.Tables.Count - 1];
//循环获得每个table文件
for (int i = 0; i < ds.Tables.Count - 1; i++)
{
//创建文件
string tablenamestr = HouseKeepingFilePath + "\\Housekeeping_" + ds.Tables[tablescount].Rows[0][i] + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
//文件路径数组
datanames[i] = tablenamestr;
//文件名数组
dataFileNames[i] = "Housekeeping_" + ds.Tables[tablescount].Rows[0][i] + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
//导出到excel文件
ExportExcel(ds.Tables[i], HouseKeepingFilePath + "\\", tablenamestr, "Sheet1");
}
//创建文件夹
string dataHouseKeepingFilePath = HouseKeepingFilePath + "\\Housekeeping_Data" + DateTime.Now.ToString("yyyyMMdd");
if (!Directory.Exists(dataHouseKeepingFilePath))//No find path
{
Directory.CreateDirectory(dataHouseKeepingFilePath);//Create a folder for a path
}
//将文件copy到文件夹
for (int i = 0; i < datanames.Length; i++)
{
if (File.Exists(datanames[i]))
{
File.Copy(datanames[i], dataHouseKeepingFilePath + "\\" + dataFileNames[i], true);
File.Delete(datanames[i]);
}
}
//创建zip文件
string HouseKeepingDatePathFilezip = HouseKeepingFilePath + "\\HouseKeeping_Data_" + DateTime.Now.ToString("yyyyMMdd") + ".zip";
if (!File.Exists(HouseKeepingDatePathFilezip))
{
FileStream ff = File.Create(HouseKeepingDatePathFilezip);
ff.Close();
}
//将文件夹打包到Zip文件
PackageFile.PackageFolder(dataHouseKeepingFilePath, HouseKeepingDatePathFilezip, true);
//Delete the folders and files that have just been created
if (Directory.Exists(dataHouseKeepingFilePath))
{
Directory.Delete(dataHouseKeepingFilePath, true);
}
}
catch (Exception ex)
{
throw;
}
}
#endregion
#region File backup and delete
public static void FileBackUpAndDeleted(DataSet dataset, string filePath, string houseKeepingFilePath)
{
try
{
//原文件存储路径
string FilePath = filePath;
//备份文件存储路径
string HouseKeepingFilePath = houseKeepingFilePath ;
//备份并压缩文件存储路径
string HouseKeepingFilePathzip = HouseKeepingFilePath;
//Dataset 是需要删除的文件名称,文件名是保存在DB中
DataSet ds = dataset;
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
//获得压缩文件的绝对路径
string HouseKeepingFilePathFilezip = HouseKeepingFilePath + "\\HouseKeeping_Attachment_" + DateTime.Now.ToString("yyyyMMdd") + ".zip";
if (!File.Exists(HouseKeepingFilePathFilezip))
{
FileStream ff = File.Create(HouseKeepingFilePathFilezip);
ff.Close();
}
//创建文件
HouseKeepingFilePath = HouseKeepingFilePath + DateTime.Now.ToString("yyyyMMddHHmmss");
if (!Directory.Exists(HouseKeepingFilePath))//If the path does not exist
{
Directory.CreateDirectory(HouseKeepingFilePath);//Create a folder for a path
}
//获得要备份的文件名的数组
string[] filenames = new string[ds.Tables[0].Rows.Count];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//FileName为DB中存储文件名的字段名称
filenames[i] = FilePath + "\\" + ds.Tables[0].Rows[i]["FileName"].ToString();
if (File.Exists(filenames[i]))
{
File.Copy(filenames[i], HouseKeepingFilePath + "\\" + ds.Tables[0].Rows[i]["FileName"].ToString(), true);
}
}
//Packaging and compressing folders
PackageFile.PackageFolder(HouseKeepingFilePath, HouseKeepingFilePathFilezip, true);
//Delete the folders and files that have just been created
if (Directory.Exists(HouseKeepingFilePath))
{
Directory.Delete(HouseKeepingFilePath, true);
}
//File deletion
DeleteMulti(filenames);
}
}
}
catch (Exception ex)
{
//add log
throw;
}
}
///
/// Delete multiple files
///
///
public static void DeleteMulti(string[] sourceFileList)
{
try
{
foreach (var item in sourceFileList)
{
if (File.Exists(item))
{
File.Delete(item);
}
}
}
catch (Exception ex)
{
throw;
}
}
#endregion
#region 导出方法
public static bool ExportExcel(DataTable dt, string templateFile, string exportFile, string sheetName = "Sheet1", int startRowIndex = 2)
{
bool flag = true;
try
{
CreateExcelExt(exportFile, sheetName);
FileInfo fi = new FileInfo(exportFile);
fi.Attributes = fi.Attributes & ~FileAttributes.ReadOnly & ~FileAttributes.Hidden;
using (SpreadsheetDocument document = SpreadsheetDocument.Open(exportFile, true, new OpenSettings() { AutoSave = true }))
{
IEnumerable sheets = document.WorkbookPart.Workbook.Descendants().Where(s => s.Name == sheetName);
if (string.IsNullOrEmpty(sheets.First().Id))
{
throw new Exception("sheet is empty");
}
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
SheetData sd = worksheetPart.Worksheet.Descendants().FirstOrDefault();
Row headerRow = new Row();
foreach (DataColumn column in dt.Columns)
{
Cell cell = new Cell()
{
DataType = CellValues.String,
CellValue = new CellValue(column.ColumnName)
};
headerRow.Append(cell);
}
sd.Append(headerRow);
int rowIndex = startRowIndex;
foreach (DataRow dr in dt.Rows)
{
Row row = new Row();
row.RowIndex = (UInt32)rowIndex++;
int colIndex = 0;
foreach (DataColumn dc in dt.Columns)
{
Cell cell = new Cell();
CellValue cv = new CellValue(FormatValue(dr[dc].ToString(), dc, cell));
cell.Append(cv);
row.Append(cell);
colIndex++;
}
sd.Append(row);
}
//Save
worksheetPart.Worksheet.Save();
document.WorkbookPart.Workbook.Save();
}
}
catch (Exception ex)
{
flag = false;
throw ex;
}
return flag;
}
public static bool CreateExcelExt(string strPathName, string sheetname)
{
try
{
using (SpreadsheetDocument m_Doc = SpreadsheetDocument.Create(strPathName, SpreadsheetDocumentType.Workbook))
{
// WorkbookPart
var m_WorkBookPart = m_Doc.AddWorkbookPart();
// Workbook
var m_WorkBook = m_WorkBookPart.Workbook = new Workbook();
// Sheets
var m_Sheets = m_WorkBook.AppendChild(new Sheets());
// ShareTable
m_WorkBookPart.AddNewPart();
var m_ShareTable = m_WorkBookPart.SharedStringTablePart.SharedStringTable = new SharedStringTable();
if (false == sheetInsert(sheetname, m_Doc, m_Sheets, m_WorkBook))
{
return false;
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
return false;
}
return true;
}
public static bool sheetInsert(string sheetName, SpreadsheetDocument m_Doc, Sheets m_Sheets, Workbook m_WorkBook)
{
try
{
WorksheetPart newWorksheetPart = m_Doc.WorkbookPart.AddNewPart();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
uint sheetID = 1;
if (m_Sheets.Descendants().Count() > 0)
{
sheetID = m_Sheets.Descendants().Select(S => S.SheetId.Value).Max() + 1;
}
Sheet newSheet = new Sheet()
{
Name = sheetName,
SheetId = sheetID,
Id = m_Doc.WorkbookPart.GetIdOfPart(newWorksheetPart),
};
m_Sheets.Append(newSheet);
var m_WorkSheetPart = newWorksheetPart;
var m_WorkSheet = m_WorkSheetPart.Worksheet;
m_WorkSheet.Save();
m_WorkBook.Save();
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
return false;
}
return true;
}
private static string FormatValue(string value, DataColumn col, Cell cell)
{
if (col.DataType.FullName == "System.Decimal" && (!string.IsNullOrEmpty(value)))
{
cell.DataType = CellValues.Number;
}
else if (col.DataType.FullName == "System.DateTime" && (!string.IsNullOrEmpty(value)))
{
cell.DataType = CellValues.String;
value = Convert.ToDateTime(value, System.Globalization.CultureInfo.CurrentCulture).ToString(System.Globalization.CultureInfo.CurrentCulture);
}
else if (col.DataType.FullName == "System.Boolean")
{
cell.DataType = CellValues.String;
value = string.IsNullOrEmpty(value) ? "" : Convert.ToBoolean(value, System.Globalization.CultureInfo.CurrentCulture) ? "True" : "False";
}
else
{
cell.DataType = CellValues.String;
}
return value;
}
#endregion
}
///
/// 1.Package folder
/// 2.Compress file and Uncompress file
/// 3.Extract Part file
///
public static class PackageFile
{
///
/// Package a folder to a zip file
///
/// The folder path
/// The zip file name full path
/// The override flag
/// Return true or false
public static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
{
if (!string.IsNullOrEmpty(folderName) && folderName.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
folderName = folderName.Remove(folderName.Length - 1);
bool result = false;
if (!Directory.Exists(folderName))
{
return result;
}
if (!overrideExisting && File.Exists(compressedFileName))
{
return result;
}
try
{
using (Package package = Package.Open(compressedFileName, FileMode.Create))
{
var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
foreach (string fileName in fileList)
{
//The path in the package is all of the subfolders after folderName
string pathInPackage;
pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(packagePartDocument.GetStream());
}
}
}
result = true;
}
catch (Exception e)
{
//throw new Exception("Error zipping folder " + folderName, e);
throw new IOException("Error zipping folder " + folderName, e);
}
return result;
}
///
/// Compress a file into a ZIP archive as the container store
///
/// The file to compress
/// The archive file
/// override existing file
/// Return true or false
public static bool CompressFile(string fileName, string compressedFileName, bool overrideExisting)
{
bool result = false;
if (!File.Exists(fileName))
{
return result;
}
if (!overrideExisting && File.Exists(compressedFileName))
{
return result;
}
try
{
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative));
using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate))
{
if (package.PartExists(partUriDocument))
{
package.DeletePart(partUriDocument);
}
PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(packagePartDocument.GetStream());
}
}
result = true;
}
catch (Exception e)
{
// throw new Exception("Error zipping file " + fileName, e);
throw new IOException("Error zipping file " + fileName, e);
}
return result;
}
///
/// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification
///
/// The folder to extract the package to
/// The package file
/// override existing files
/// Return true or false
public static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting)
{
bool result = false;
try
{
if (!File.Exists(compressedFileName))
{
return result;
}
DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
if (!directoryInfo.Exists)
directoryInfo.Create();
using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart packagePart in package.GetParts())
{
ExtractPart(packagePart, folderName, overrideExisting);
}
}
result = true;
}
catch (Exception e)
{
//throw new Exception("Error unzipping file " + compressedFileName, e);
throw new IOException("Error unzipping file " + compressedFileName, e);
}
return result;
}
///
/// Extract package part
///
/// The PackagePart object
/// The target path
/// override existing files
private static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)
{
//string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/');
string stringPart = targetDirectory + packagePart.Uri.ToString().Replace('\\', '/');
if (!Directory.Exists(Path.GetDirectoryName(stringPart)))
Directory.CreateDirectory(Path.GetDirectoryName(stringPart));
if (!overrideExisting && File.Exists(stringPart))
return;
using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))
{
packagePart.GetStream().CopyTo(fileStream);
}
}
}
}