CSharp: word,excel,powerpoint convert to pdf,hrml etc using Aspose.Office
/// <summary>
/// 目标文件类型
/// Aspose是商业软件需要购买
/// </summary>
public enum FileFormat
{
None,
Pdf,
Html,
Text,
Doc,
Docx,
Xls,
Xlsx,
CSV,
PPT,
PPTx,
SVG,
Webp,
Rtf,
Dwg,
Psd
}
/// <summary>
/// 文件转换
/// geovindu,Geovin Du,涂聚文,塗聚文
/// 底部有水印,是商业软件需要购买
/// 有时间慢慢优化,不断完善
/// 20251024
/// </summary>
public class AsposeOfficeHelper
{
/// <summary>
/// 文件转换
/// 其他文件类型自我优化
///
/// </summary>
/// <param name="inpFile">源文件</param>
/// <param name="outFile">目标文件</param>
/// <param name="fileFormat">目标转换文件类型</param>
/// <returns></returns>
public static bool DuConvert(string inpFile, string outFile, FileFormat fileFormat)
{
int i = outFile.LastIndexOf("\\");
int j = outFile.LastIndexOf(".");
string FileName = outFile.Substring(i + 1, j - (i + 1));
string ExtendName = outFile.Substring(j + 1);
//考虑扩展名
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
switch (fileFormat)
{
case FileFormat.Pdf:
isNeedConvert = ConvertPdf(inpFile, outFile);
break;
case FileFormat.Html:
isNeedConvert = ConvertHtml(inpFile, outFile);
break;
case FileFormat.Text:
isNeedConvert = ConvertText(inpFile, outFile);
break;
case FileFormat.Xls:
isNeedConvert = ConvertXls(inpFile, outFile);
break;
case FileFormat.Xlsx:
isNeedConvert = ConvertXlsx(inpFile, outFile);
break;
case FileFormat.CSV:
isNeedConvert = ConvertCSV(inpFile, outFile);
break;
case FileFormat.Webp:
isNeedConvert = ConvertWebp(inpFile, outFile);
break;
case FileFormat.Doc:
isNeedConvert = ConvertDoc(inpFile, outFile);
break;
case FileFormat.Docx:
isNeedConvert = ConvertDocx(inpFile, outFile);
break;
case FileFormat.SVG:
isNeedConvert = ConvertSvg(inpFile, outFile);
break;
case FileFormat.Rtf:
isNeedConvert = ConvertRtf(inpFile, outFile);
break;
default:
isNeedConvert = false;
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPdf(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".doc":
isNeedConvert = ConvertDocToPdf(inpFile, outFile);
break;
case ".docx":
isNeedConvert = ConvertDocxToPdf(inpFile, outFile);
break;
case ".ppt":
isNeedConvert = ConvertPPTToPdf(inpFile, outFile);
break;
case ".pptx":
isNeedConvert = ConvertPPTxToPdf(inpFile, outFile);
break;
case ".xls":
isNeedConvert = ConvertXlsToPdf(inpFile, outFile);
break;
case ".xlsx":
isNeedConvert = ConvertXlsxToPdf(inpFile, outFile);
break;
case ".html":
isNeedConvert = ConvertHtmlToPdf(inpFile, outFile);
break;
case ".htm":
isNeedConvert = ConvertHtmlToPdf(inpFile, outFile);
break;
case ".txt":
isNeedConvert = ConvertTextToPdf(inpFile, outFile);
break;
case ".jpg":
isNeedConvert = ConvertJpgToPdf(inpFile, outFile);
break;
case ".png":
isNeedConvert = ConvertPngToPdf(inpFile, outFile);
break;
case ".gif":
isNeedConvert = ConvertGifToPdf(inpFile, outFile);
break;
case ".svg":
isNeedConvert = ConvertSvgToPdf(inpFile, outFile);
break;
case ".rtf":
isNeedConvert = ConvertRtfToPdf(inpFile, outFile);
break;
case ".psd":
isNeedConvert = ConvertPsdToPdf(inpFile, outFile);
break;
case ".dwg":
isNeedConvert = ConvertDwgToPdf(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertHtml(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".doc":
isNeedConvert = ConvertDocToHtml(inpFile, outFile);
break;
case ".docx":
isNeedConvert = ConvertDocxToHtml(inpFile, outFile);
break;
case ".ppt":
isNeedConvert = ConvertPPTToHtml(inpFile, outFile);
break;
case ".pptx":
isNeedConvert = ConvertPPTxToHtml(inpFile, outFile);
break;
case ".xls":
isNeedConvert = ConvertXlsToHtml(inpFile, outFile);
break;
case ".xlsx":
isNeedConvert = ConvertXlsxToHtml(inpFile, outFile);
break;
case ".html":
isNeedConvert = false;
break;
case ".htm":
isNeedConvert = false;
break;
case ".pdf":
isNeedConvert = ConvertPdfToHtml(inpFile, outFile);
break;
case ".rtf":
isNeedConvert = ConvertRtfToHtml(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertText(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".doc":
isNeedConvert = ConvertDocToText(inpFile, outFile);
break;
case ".docx":
isNeedConvert = ConvertDocxToText(inpFile, outFile);
break;
case ".ppt":
isNeedConvert = false;// ConvertPPTToText(inpFile, outFile);
break;
case ".pptx":
isNeedConvert = false;// ConvertPPTXToText(inpFile, outFile);
break;
case ".xls":
isNeedConvert = ConvertXlsToText(inpFile, outFile);
break;
case ".xlsx":
isNeedConvert = ConvertXlsxToText(inpFile, outFile);
break;
case ".html":
isNeedConvert = false;//ConvertHtmlToText(inpFile, outFile);
break;
case ".htm":
isNeedConvert = false;//ConvertHtmlToText(inpFile, outFile);
break;
case ".pdf":
isNeedConvert = ConvertPdfToText(inpFile, outFile);
break;
case ".rtf":
isNeedConvert = false;//ConvertRtfToText(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDoc(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".txt":
isNeedConvert = false;// ConvertTextToDoc(inpFile, outFile);
break;
case ".pdf":
isNeedConvert = ConvertPdfToDoc(inpFile, outFile);
break;
case ".html":
isNeedConvert = ConvertHtmlToDoc(inpFile, outFile);
break;
case ".Docx":
isNeedConvert = ConvertDocxToDoc(inpFile, outFile);
break;
case ".rtf":
isNeedConvert = false;// ConvertRtfToDoc(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocx(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".doc":
isNeedConvert = ConvertDocToDocx(inpFile, outFile);
break;
case ".xsl":
isNeedConvert = ConvertXlsToDocx(inpFile, outFile);
break;
case ".xslx":
isNeedConvert = ConvertXlsxToDocx(inpFile, outFile);
break;
case ".txt":
isNeedConvert = false;// ConvertTextToDocx(inpFile, outFile);
break;
case ".pdf":
isNeedConvert = ConvertPdfToDocx(inpFile, outFile);
break;
case ".html":
isNeedConvert = ConvertHtmlToDocx(inpFile, outFile);
break;
case ".rtf":
isNeedConvert = false;//ConvertRtfToDocx(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertCSV(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".xls":
isNeedConvert = ConvertXlsToCsv(inpFile, outFile);
break;
case ".xlsx":
isNeedConvert = ConvertXlsxToCsv(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXls(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".csv":
isNeedConvert = ConvertCsvToXls(inpFile, outFile);
break;
case ".xlsx":
isNeedConvert = ConvertXlsxToXls(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsx(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".xls":
isNeedConvert = ConvertXlsToXlsx(inpFile, outFile);
break;
case ".csv":
isNeedConvert = ConvertCsvToXlsx(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertRtf(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".doc":
isNeedConvert = ConvertDocToRtf(inpFile, outFile);
break;
case ".docx":
isNeedConvert = ConvertDocxToRtf(inpFile, outFile);
break;
case ".ppt":
isNeedConvert = false;// ConvertPPTToRtf(inpFile, outFile);
break;
case ".pptx":
isNeedConvert = false;//ConvertPPTxToRtf(inpFile, outFile);
break;
case ".xls":
isNeedConvert = false;//ConvertXlsToRtf(inpFile, outFile);
break;
case ".xlsx":
isNeedConvert = false;//ConvertXlsxToRtf(inpFile, outFile);
break;
case ".html":
isNeedConvert = ConvertHtmlToRtf(inpFile, outFile);
break;
case ".htm":
isNeedConvert = ConvertHtmlToRtf(inpFile, outFile);
break;
case ".pdf":
isNeedConvert = false;// ConvertPdfToRtf(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertWebp(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".jpg":
isNeedConvert = ConvertImageToWebp(inpFile, outFile);
break;
case ".png":
isNeedConvert = ConvertImageToWebp(inpFile, outFile);
break;
case ".gif":
isNeedConvert = ConvertImageToWebp(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertSvg(string inpFile, string outFile)
{
bool isNeedConvert = false;
if (File.Exists(inpFile))
{
var fileInfo = new FileInfo(inpFile); //获上传源文件的扩展名
switch (fileInfo.Extension.ToLower())
{
case ".jpg":
isNeedConvert = ConvertImagedToSvg(inpFile, outFile);// ConvertJpgToSvg(inpFile, outFile);
break;
case ".png":
isNeedConvert = ConvertPngToSvg(inpFile, outFile);
break;
case ".gif":
isNeedConvert = ConvertImagedToSvg(inpFile, outFile);// ConvertGifToSvg(inpFile, outFile);
break;
}
}
return isNeedConvert;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertHtmlToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the HTML file into a document using HtmlLoadOptions
var options = new Aspose.Pdf.HtmlLoadOptions();
// Open HTML document
using (var document = new Aspose.Pdf.Document(inpFile, options))
{
// Save PDF document
document.Save(outFile);
}
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertHtmlToPdfTwo(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the HTML file into a document using HtmlLoadOptions
var document = new Aspose.Html.HTMLDocument(inpFile);
var options = new Aspose.Html.Saving.PdfSaveOptions();
Aspose.Html.Converters.Converter.ConvertHTML(document, options, outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertHtmlToDocx(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the HTML file into a document using HtmlLoadOptions
var document = new Aspose.Html.HTMLDocument(inpFile);
var options = new Aspose.Html.Saving.DocSaveOptions();
Aspose.Html.Converters.Converter.ConvertHTML(document, options, outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertHtmlToRtf(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the HTML file into a document using HtmlLoadOptions
using (MemoryStream inpMS = new MemoryStream(File.ReadAllBytes(inpFile)))
{
Aspose.Words.Document doc = new Aspose.Words.Document(inpMS);
doc.Save(outFile, Aspose.Words.SaveFormat.Rtf);
// doc.Save(inpMS, Aspose.Words.SaveFormat.Rtf);
// Rewind the stream position back to zero so it is ready for the next reader.
// inpMS.Position = 0;
//File.WriteAllBytes(outFile, inpMS.ToArray());
}
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertHtmlToDoc(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the HTML file into a document using HtmlLoadOptions
var document = new Aspose.Html.HTMLDocument(inpFile);
var options = new Aspose.Html.Saving.DocSaveOptions();
Aspose.Html.Converters.Converter.ConvertHTML(document, options, outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertTextToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var tr = new StreamReader(inpFile);
var doc = new Aspose.Pdf.Document();
var page = doc.Pages.Add();
var text = new TextFragment(tr.ReadToEnd());
page.Paragraphs.Add(text);
doc.Save(outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
/// ConvertRtfToPdf
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocxToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Pdf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocToDocx(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Docx);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocxToDoc(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Doc);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertRtfToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
//多个文件
//var fileNames = new List<string> { "Input1.rtf", "Input2.rtf" };
//var output = new Document();
//// 在追加之前从目标文档中删除所有内容。
//output.RemoveAllChildren();
//foreach (string fileName in fileNames)
//{
// var input = new Document(fileName);
// // 将源文档附加到目标文档的末尾。
// output.AppendDocument(input, ImportFormatMode.KeepSourceFormatting);
//}
//output.Save("Output.pdf");
var input = new Aspose.Words.Document(inpFile);
input.Save(outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertRtfToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
var input = new Aspose.Words.Document(inpFile);
//Aspose.Words.Saving.HtmlSaveOptions options = new Aspose.Words.Saving.HtmlSaveOptions()
//{
// HtmlVersion = HtmlVersion.XHtml,
// ExportXhtmlTransitional = true,
// PrettyFormat = true
//};
Aspose.Words.Saving.HtmlFixedSaveOptions options = new Aspose.Words.Saving.HtmlFixedSaveOptions()
{
ExportEmbeddedImages = true,
ExportEmbeddedCss = true,
PrettyFormat = true
};
input.Save(outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Pdf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocxToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Html);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Html);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocToText(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Text);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocxToText(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Text);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocToRtf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Rtf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDocxToRtf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Words.Document(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Words.SaveFormat.Rtf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Pdf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Html);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsToDocx(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Docx);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsxToDocx(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Docx);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsToJson(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Json);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsToText(string inpFile, string outFile)
{
bool ok = false;
try
{
//Load your source workbook
var workbook = new Aspose.Cells.Workbook(inpFile);
//0-byte array
byte[] workbookData = new byte[0];
//Text save options. You can use any type of separator
var opts = new Aspose.Cells.TxtSaveOptions();
opts.Separator = '\t';
//Copy each worksheet data in text format inside workbook data array
for (int idx = 0; idx < workbook.Worksheets.Count; idx++)
{
//Save the active worksheet into text format
MemoryStream ms = new MemoryStream();
workbook.Worksheets.ActiveSheetIndex = idx;
workbook.Save(ms, opts);
//Save the worksheet data into sheet data array
ms.Position = 0;
byte[] sheetData = ms.ToArray();
//Combine this worksheet data into workbook data array
byte[] combinedArray = new byte[workbookData.Length + sheetData.Length];
Array.Copy(workbookData, 0, combinedArray, 0, workbookData.Length);
Array.Copy(sheetData, 0, combinedArray, workbookData.Length, sheetData.Length);
workbookData = combinedArray;
}
//Save entire workbook data into file
File.WriteAllBytes(outFile, workbookData);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsxToText(string inpFile, string outFile)
{
bool ok = false;
try
{
//Load your source workbook
var workbook = new Aspose.Cells.Workbook(inpFile);
//0-byte array
byte[] workbookData = new byte[0];
//Text save options. You can use any type of separator
var opts = new Aspose.Cells.TxtSaveOptions();
opts.Separator = '\t';
//Copy each worksheet data in text format inside workbook data array
for (int idx = 0; idx < workbook.Worksheets.Count; idx++)
{
//Save the active worksheet into text format
var ms = new MemoryStream();
workbook.Worksheets.ActiveSheetIndex = idx;
workbook.Save(ms, opts);
//Save the worksheet data into sheet data array
ms.Position = 0;
byte[] sheetData = ms.ToArray();
//Combine this worksheet data into workbook data array
byte[] combinedArray = new byte[workbookData.Length + sheetData.Length];
Array.Copy(workbookData, 0, combinedArray, 0, workbookData.Length);
Array.Copy(sheetData, 0, combinedArray, workbookData.Length, sheetData.Length);
workbookData = combinedArray;
}
//Save entire workbook data into file
File.WriteAllBytes(outFile, workbookData);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsxToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Pdf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
/// ConvertXlsxToXls
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsToXlsx(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Xlsx);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsxToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Html);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsToCsv(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Csv);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsxToCsv(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Cells.SaveFormat.Csv);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertXlsxToXls(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Cells.Workbook(inpFile);
// Save the document in HTML format.
doc.Save(outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPPTToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Slides.Presentation(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Slides.Export.SaveFormat.Pdf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPPTToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Slides.Presentation(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Slides.Export.SaveFormat.Html5);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPPTToJpg(string inpFile, string outFile)
{
bool ok = false;
try
{
using (var presentation = new Aspose.Slides.Presentation(inpFile))
{
for (int i = 0; i < presentation.Slides.Count; i++)
{
// Generate thumbnail for each slide
using (var bitmap = presentation.Slides[i].GetThumbnail(1f, 1f))
{
// Save each slide as a separate image
bitmap.Save($"Slide_{i + 1}.jpg"); //, System.Drawing.Imaging.ImageFormat.Jpeg
}
}
}
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPPTxToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Slides.Presentation(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Slides.Export.SaveFormat.Pdf);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPPTxToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
var doc = new Aspose.Slides.Presentation(inpFile);
// Save the document in HTML format.
doc.Save(outFile, Aspose.Slides.Export.SaveFormat.Html5);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPdfToHtml(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the source PDF document
var pdfDocument = new Aspose.Pdf.Document(inpFile);
// Save the PDF as a Word document (DOCX format)
pdfDocument.Save(outFile, Aspose.Pdf.SaveFormat.Html);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPdfToText(string inpFile, string outFile)
{
bool ok = false;
try
{
//string[] pdfFiles = { "sample1.pdf", "sample2.pdf" };
//var extractor = new TextExtractor();
//var options = new TextExtractorOptions(TextExtractorOptions.TextFormattingMode.Raw);
//foreach (var file in pdfFiles)
//{
// options.AddInput(new FileDataSource(file));
//}
//var resultContainer = extractor.Process(options);
//for (int i = 0; i < resultContainer.ResultCollection.Count; i++)
//{
// string text = resultContainer.ResultCollection[i].ToString();
// Console.WriteLine(text);
//}
//2
//var extractor = new TextExtractor();
//var options = new TextExtractorOptions(TextExtractorOptions.TextFormattingMode.Pure);
//options.AddInput(new FileDataSource(inpFile));
//var resultContainer = extractor.Process(options);
//string extractedText = resultContainer.ResultCollection[0].ToString();
//// Save the extracted text to a file
//File.WriteAllText(outFile, extractedText);
//3
// Load the PDF document
var pdfDocument = new Aspose.Pdf.Document(inpFile);
// StringBuilder to hold the extracted text
var builder = new StringBuilder();
// Loop through all the pages in the PDF
foreach (var pdfPage in pdfDocument.Pages)
{
// Process each page for text extraction
using (MemoryStream textStream = new MemoryStream())
{
// Create a text device for text extraction
var textDevice = new TextDevice();
// Set text extraction options to 'Pure' mode
var textExtOptions = new TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure);
textDevice.ExtractionOptions = textExtOptions;
// Extract text from the current page and save it to the memory stream
textDevice.Process(pdfPage, textStream);
// Convert memory stream to text
string extractedText = Encoding.Unicode.GetString(textStream.ToArray());
// Append the extracted text to the StringBuilder
builder.Append(extractedText);
}
}
// Save the extracted text to a file
File.WriteAllText(outFile, builder.ToString());
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPdfToDoc(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the source PDF document
var pdfDocument = new Aspose.Pdf.Document(inpFile);
// Save the PDF as a Word document (DOCX format)
pdfDocument.Save(outFile, Aspose.Pdf.SaveFormat.Doc);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPdfToDocx(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the source PDF document
var pdfDocument = new Aspose.Pdf.Document(inpFile);
// Save the PDF as a Word document (DOCX format)
pdfDocument.Save(outFile, Aspose.Pdf.SaveFormat.DocX);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertJpgToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
// Create PDF document
using (var document = new Aspose.Pdf.Document())
{
// Add page
var page = document.Pages.Add();
var image = new Aspose.Pdf.Image();
// Load JPEG file
image.File = inpFile;
// Read Height of input image
page.PageInfo.Height = image.BitmapSize.Height;
// Read Width of input image
page.PageInfo.Width = image.BitmapSize.Width;
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Right = 0;
page.PageInfo.Margin.Left = 0;
page.Paragraphs.Add(image);
// Save PDF document
document.Save(outFile);
}
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertGifToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
// Create PDF document
using (var document = new Aspose.Pdf.Document())
{
// Add page
var page = document.Pages.Add();
var image = new Aspose.Pdf.Image();
// Load sample GIF image file
image.File = inpFile;
page.Paragraphs.Add(image);
// Save PDF document
document.Save(outFile);
}
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPngToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
// Create PDF document
using (var document = new Aspose.Pdf.Document())
{
// Add page
var page = document.Pages.Add();
var image = new Aspose.Pdf.Image();
// Load PNG file
image.File = inpFile;
// Read Height of input image
page.PageInfo.Height = image.BitmapSize.Height;
// Read Width of input image
page.PageInfo.Width = image.BitmapSize.Width;
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Right = 0;
page.PageInfo.Margin.Left = 0;
page.Paragraphs.Add(image);
// Save PDF document
document.Save(outFile);
}
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertPsdToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
var loadOptions = new PsdLoadOptions() { LoadEffectsResource = true };
PsdImage image = (PsdImage)Aspose.PSD.Image.Load(inpFile, loadOptions);
var pdfOptions = new Aspose.PSD.ImageOptions.PdfOptions();
// Customize pdfOptions as needed (compression, encryption, etc.)
image.Save(outFile, pdfOptions);
image.Dispose();
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertDwgToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load a CAD drawing in an instance of CadImage
using (CadImage cadImage = (CadImage)Aspose.CAD.Image.Load(inpFile))
{
// Create an instance of PdfOptions
Aspose.CAD.ImageOptions.PdfOptions pdfOptions = new Aspose.CAD.ImageOptions.PdfOptions();
// Create an instance of CadRasterizationOptions and set its various properties
CadRasterizationOptions cadRasterizationOptions = new CadRasterizationOptions();
cadRasterizationOptions.PageWidth = 1600;
cadRasterizationOptions.PageHeight = 1600;
// cadRasterizationOptions.CenterDrawing = true;
//cadRasterizationOptions.ScaleMethod = ScaleType.Center;
// Set the VectorRasterizationOptions property
pdfOptions.VectorRasterizationOptions = cadRasterizationOptions;
// Export the CAD drawing to PDF format
cadImage.Save(outFile, pdfOptions);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertImageToWebp(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the image using ImageSharp
using (var image = SixLabors.ImageSharp.Image.Load(inpFile))
{
// Save the image in WebP format
image.Save(outFile, new WebpEncoder());
ok = true;
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertImageToWebpTwo(string inpFile, string outFile)
{
bool ok = false;
try
{
// Load the image using Aspose.Imaging
using (var image = Aspose.Imaging.Image.Load(inpFile))
{
// Save the image in WebP format
image.Save(outFile, new Aspose.Imaging.ImageOptions.WebPOptions());
ok = true;
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertSvgToPdf(string inpFile, string outFile)
{
bool ok = false;
try
{
// 加载 SVG 文件
var document = new SVGDocument(inpFile);
// 配置保存选项
var options = new Aspose.Svg.Saving.PdfSaveOptions();
// 转换并保存为 PDF 文件
Aspose.Svg.Converters.Converter.ConvertSVG(document, options, outFile);
ok = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="fileOriginPath"></param>
/// <param name="fileSavePath"></param>
/// <returns></returns>
static bool ConvertPngToSvg(string fileOriginPath, string fileSavePath)
{
bool ok = true;
try
{
using (var image = Aspose.Imaging.Image.Load(fileOriginPath))
{
var svgOptions = new Aspose.Imaging.ImageOptions.SvgOptions();
var svgRasterizationOptions = new Aspose.Imaging.ImageOptions.SvgRasterizationOptions
{
PageWidth = image.Width,
PageHeight = image.Height
};
svgOptions.VectorRasterizationOptions = svgRasterizationOptions;
image.Save(fileSavePath, svgOptions);
ok = true;
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="fileOriginPath"></param>
/// <param name="fileSavePath"></param>
/// <returns></returns>
static bool ConvertImagedToSvg(string fileOriginPath, string fileSavePath)
{
bool ok = true;
try
{
using (var image = Aspose.Imaging.Image.Load(fileOriginPath))
{
var svgOptions = new Aspose.Imaging.ImageOptions.SvgOptions();
var svgRasterizationOptions = new Aspose.Imaging.ImageOptions.SvgRasterizationOptions
{
PageWidth = image.Width,
PageHeight = image.Height
};
svgOptions.VectorRasterizationOptions = svgRasterizationOptions;
image.Save(fileSavePath, svgOptions);
ok = true;
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="csvFilePath"></param>
/// <param name="xlsxFilePath"></param>
/// <returns></returns>
public static bool ConvertCsvToXlsx(string inpFile, string outFile)
{
bool ok = false;
try
{
// Read CSV lines
var lines = File.ReadAllLines(inpFile);
// Create Excel document
using (var document = SpreadsheetDocument.Create(outFile, SpreadsheetDocumentType.Workbook))
{
var workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());
var sheets = document.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet()
{
Id = document.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Populate data from CSV
foreach (var line in lines)
{
DocumentFormat.OpenXml.Spreadsheet.Row row = new DocumentFormat.OpenXml.Spreadsheet.Row();
var cells = line.Split(',');
foreach (var cellValue in cells)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell()
{
DataType = CellValues.String,
CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(cellValue)
};
row.Append(cell);
}
sheetData.Append(row);
}
workbookPart.Workbook.Save();
ok = true;
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
return ok;
}
/// <summary>
///
/// </summary>
/// <param name="inpFile"></param>
/// <param name="outFile"></param>
/// <returns></returns>
static bool ConvertCsvToXls(string inpFile, string outFile)
{
bool ok = false;
var encoding = Encoding.UTF8;
char delimiter = ',';
try
{
var dataTable = ReadCsv(inpFile, encoding, delimiter);
ok = ConvertDataTableToXls(dataTable, outFile);
}
catch (Exception ex)
{
ex.Message.ToString();
}
return ok;
}
/// <summary>
/// Reads a CSV file and returns its contents as a DataTable
/// </summary>
/// <param name="filePath"></param>
/// <param name="encoding"></param>
/// <param name="delimiter"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
static DataTable ReadCsv(string filePath, Encoding encoding, char delimiter)
{
try
{
using (var reader = new StreamReader(filePath, encoding))
using (var csv = new CsvReader(reader, new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = delimiter.ToString(),
HasHeaderRecord = true,
IgnoreBlankLines = true,
TrimOptions = CsvHelper.Configuration.TrimOptions.Trim
}))
{
using (var dr = new CsvDataReader(csv))
{
var dt = new DataTable();
dt.Load(dr);
return dt;
}
}
}
catch (Exception ex)
{
throw new Exception($"Failed to read CSV file: {ex.Message}", ex);
}
}
/// <summary>
///
/// </summary>
/// <param name="dataTable"></param>
/// <param name="outputPath"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
static bool ConvertDataTableToXls(DataTable dataTable, string outputPath)
{
bool ok = false;
try
{
// Create a new spreadsheet document
using (var document = SpreadsheetDocument.Create(outputPath, SpreadsheetDocumentType.Workbook))
{
// Add a WorkbookPart to the document
var workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
// Add a WorksheetPart to the WorkbookPart
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());
// Add Sheets to the Workbook
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
// Append a new worksheet and associate it with the workbook
var sheet = new Sheet()
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet);
// Get the SheetData object
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Add header row
var headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (DataColumn column in dataTable.Columns)
{
var cell = CreateCell(column.ColumnName, CellValues.String);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
// Add data rows
foreach (DataRow row in dataTable.Rows)
{
var dataRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (var item in row.ItemArray)
{
CellValues cellType = GetCellValueType(item);
string cellValue = GetCellValueAsString(item, cellType);
var cell = CreateCell(cellValue, cellType);
dataRow.AppendChild(cell);
}
sheetData.AppendChild(dataRow);
}
// Save the workbook
workbookPart.Workbook.Save();
ok = true;
}
}
catch (Exception ex)
{
throw new Exception($"Failed to create XLS file: {ex.Message}", ex);
}
return ok;
}
/// <summary>
/// Creates a new Excel cell with the specified value and type
/// </summary>
/// <param name="value"></param>
/// <param name="cellType"></param>
/// <returns></returns>
private static DocumentFormat.OpenXml.Spreadsheet.Cell CreateCell(string value, CellValues cellType)
{
var cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = new EnumValue<CellValues>(cellType);
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(value);
return cell;
}
/// <summary>
/// Determines the cell value type based on the object type
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static DocumentFormat.OpenXml.Spreadsheet.CellValues GetCellValueType(object value)
{
if (value == DBNull.Value)
return DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
Type type = value.GetType();
if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte))
return DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
else if (type == typeof(float) || type == typeof(double) || type == typeof(decimal))
return DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
else if (type == typeof(DateTime))
return DocumentFormat.OpenXml.Spreadsheet.CellValues.Date;
else if (type == typeof(bool))
return DocumentFormat.OpenXml.Spreadsheet.CellValues.Boolean;
else
return DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="cellType"></param>
/// <returns></returns>
private static string GetCellValueAsString(object value, DocumentFormat.OpenXml.Spreadsheet.CellValues cellType)
{
if (value == DBNull.Value || value == null)
return string.Empty;
if (cellType == DocumentFormat.OpenXml.Spreadsheet.CellValues.Boolean)
{
return (value is bool boolVal && boolVal) ? "1" : "0";
}
else if (cellType == DocumentFormat.OpenXml.Spreadsheet.CellValues.Number)
{
if (value is DateTime dateVal)
{
return dateVal.ToOADate().ToString(CultureInfo.InvariantCulture);
}
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
else if (cellType == DocumentFormat.OpenXml.Spreadsheet.CellValues.String ||
cellType == DocumentFormat.OpenXml.Spreadsheet.CellValues.SharedString)
{
return Convert.ToString(value) ?? string.Empty;
}
else
{
return string.Empty;
}
}
}
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号