initial version with inspection edition
This commit is contained in:
220
IronIntelContractorBusiness/ExportExcel/ConvertFormat.cs
Normal file
220
IronIntelContractorBusiness/ExportExcel/ConvertFormat.cs
Normal file
@ -0,0 +1,220 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace IronIntel.Contractor
|
||||
{
|
||||
public class ConvertFormat
|
||||
{
|
||||
/// <summary>
|
||||
/// 本函数将c#格式转换为excel格式,在转换时只允许一个格式中出现{0}或{0:xxx}之类的一次,多余的抛弃。
|
||||
/// </summary>
|
||||
/// <param name="csharpFormat"></param>
|
||||
/// <returns></returns>
|
||||
public static string ConvertFormatFromCSharpToExcel(string csharpFormat, CellDataType DataType)
|
||||
{
|
||||
if (string.IsNullOrEmpty(csharpFormat)) return "";
|
||||
|
||||
#region 验证格式是否合格。
|
||||
switch (DataType)
|
||||
{
|
||||
case CellDataType.Bool:
|
||||
if (!string.IsNullOrEmpty(csharpFormat))
|
||||
{
|
||||
string[] fors = csharpFormat.Split(';');
|
||||
csharpFormat = "\"" + string.Join("\";\"", fors.ToArray()) + "\"";
|
||||
if (fors.Length == 2)
|
||||
{
|
||||
csharpFormat = csharpFormat + ";" + "\"" + fors[1] + "\"";
|
||||
}
|
||||
}
|
||||
break;
|
||||
case CellDataType.Date:
|
||||
try
|
||||
{
|
||||
string.Format(csharpFormat, DateTime.Now);
|
||||
}
|
||||
catch
|
||||
{
|
||||
csharpFormat = "";
|
||||
}
|
||||
break;
|
||||
case CellDataType.Guid:
|
||||
break;
|
||||
case CellDataType.Integer:
|
||||
try
|
||||
{
|
||||
string.Format(csharpFormat, 1234);
|
||||
}
|
||||
catch
|
||||
{
|
||||
csharpFormat = "";
|
||||
}
|
||||
break;
|
||||
case CellDataType.Float:
|
||||
try
|
||||
{
|
||||
string.Format(csharpFormat, 1234.567890);
|
||||
}
|
||||
catch
|
||||
{
|
||||
csharpFormat = "";
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
#endregion
|
||||
|
||||
string cshxp = csharpFormat;
|
||||
string excelFormat = "";
|
||||
string pattern = @"\{0\}|\{0:[^\}]+\}";
|
||||
Regex reg = new Regex(pattern);
|
||||
MatchCollection mc = reg.Matches(csharpFormat);
|
||||
if (mc.Count > 0)
|
||||
{
|
||||
//将多余的格式串去掉。
|
||||
for (int i = 1; i < mc.Count; i++)
|
||||
{
|
||||
cshxp = cshxp.Replace(mc[i].Value, "");
|
||||
}
|
||||
|
||||
if (string.Equals(mc[0].Value, "{0}", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
int first = cshxp.IndexOf(mc[0].Value);
|
||||
|
||||
//当格式为{0}时,设置FIC需要的默认格式。
|
||||
string ft = "General";
|
||||
if (DataType == CellDataType.Float)
|
||||
{
|
||||
ft = "0.00";
|
||||
}
|
||||
else if (DataType == CellDataType.Integer)
|
||||
{
|
||||
ft = "0";
|
||||
}
|
||||
else if (DataType == CellDataType.Date)
|
||||
{
|
||||
ft = "MM-dd-yyyy";
|
||||
}
|
||||
else if (DataType == CellDataType.Bool)
|
||||
{
|
||||
ft = "True\";\"False\";\"False";
|
||||
}
|
||||
|
||||
excelFormat = "\"" + cshxp.Substring(0, first) + "\"" + ft + "\"" + cshxp.Substring(first + 3) + "\"";
|
||||
}
|
||||
else
|
||||
{
|
||||
int first = cshxp.IndexOf(mc[0].Value);
|
||||
string format = mc[0].Value.Replace("{0:", "");
|
||||
format = format.Replace("}", "");
|
||||
|
||||
string[] strs = format.Split(';');
|
||||
string preText = cshxp.Substring(0, first);
|
||||
string postText = cshxp.Substring(first + mc[0].Value.Length);
|
||||
|
||||
string str2 = "";
|
||||
foreach (string str in strs)
|
||||
{
|
||||
str2 = str;
|
||||
if (DataType == CellDataType.Date)
|
||||
{
|
||||
str2 = ConvertSpecialDateFormat(str);
|
||||
}
|
||||
if (string.IsNullOrEmpty(excelFormat))
|
||||
{
|
||||
excelFormat = "\"" + preText + "\"" + str2 + "\"" + postText + "\"";
|
||||
}
|
||||
else
|
||||
{
|
||||
string tmpFormat = "\"" + preText + "\"" + str2 + "\"" + postText + "\"";
|
||||
excelFormat = excelFormat + ";" + tmpFormat;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
excelFormat = cshxp;
|
||||
}
|
||||
|
||||
return excelFormat;
|
||||
}
|
||||
|
||||
private static string ConvertSpecialDateFormat(string format)
|
||||
{
|
||||
string result = format;
|
||||
//AM/PM:tt
|
||||
result = result.Replace("tt", "AM/PM");
|
||||
|
||||
//fff:
|
||||
string pattern = @"\.f+";
|
||||
Regex reg = new Regex(pattern);
|
||||
MatchCollection mc = reg.Matches(result);
|
||||
foreach (Match mt in mc)
|
||||
{
|
||||
if (mt.Value == null) continue;
|
||||
|
||||
string x0 = "";
|
||||
int num = mt.Value.Substring(1).Length;
|
||||
while (num > 0)
|
||||
{
|
||||
x0 += "0";
|
||||
num--;
|
||||
}
|
||||
result = result.Replace(mt.Value, "." + x0);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool CheckIfCSharpFormatIsValid(string format)
|
||||
{
|
||||
bool result = false;
|
||||
try
|
||||
{
|
||||
FormatDouble(format);
|
||||
return true; ;
|
||||
}
|
||||
catch { }
|
||||
|
||||
try
|
||||
{
|
||||
FormatDateTime(format);
|
||||
return true; ;
|
||||
}
|
||||
catch { }
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void FormatDouble(string format)
|
||||
{
|
||||
double x = 12345.7890;
|
||||
try
|
||||
{
|
||||
string.Format(format, x);
|
||||
}
|
||||
catch
|
||||
{
|
||||
x.ToString(format);
|
||||
}
|
||||
}
|
||||
|
||||
private static void FormatDateTime(string format)
|
||||
{
|
||||
DateTime now = DateTime.Now;
|
||||
try
|
||||
{
|
||||
string.Format(format, now);
|
||||
}
|
||||
catch
|
||||
{
|
||||
now.ToString(format);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
844
IronIntelContractorBusiness/ExportExcel/ExcelXlsx.cs
Normal file
844
IronIntelContractorBusiness/ExportExcel/ExcelXlsx.cs
Normal file
@ -0,0 +1,844 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using Ap = DocumentFormat.OpenXml.ExtendedProperties;
|
||||
using Vt = DocumentFormat.OpenXml.VariantTypes;
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using A = DocumentFormat.OpenXml.Drawing;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace IronIntel.Contractor
|
||||
{
|
||||
internal class ExcelXlsx
|
||||
{
|
||||
public ExcelXlsx() { }
|
||||
|
||||
private Dictionary<string, UInt32Value> _fontIndexCache = new Dictionary<string, UInt32Value>();
|
||||
private Dictionary<string, UInt32Value> _fillIndexCache = new Dictionary<string, UInt32Value>();
|
||||
private Dictionary<string, UInt32Value> _borderIndexCache = new Dictionary<string, UInt32Value>();
|
||||
private Dictionary<string, UInt32Value> _formatIndexCache = new Dictionary<string, UInt32Value>();
|
||||
|
||||
// Creates a SpreadsheetDocument.
|
||||
public void CreatePackage(MemoryStream ms, COpenXmlExcelSheet edata)
|
||||
{
|
||||
using (SpreadsheetDocument package = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
|
||||
{
|
||||
CExcelSheet excelSheetData = ConvertData(edata);
|
||||
CreateParts(package, excelSheetData);
|
||||
}
|
||||
}
|
||||
|
||||
private CExcelSheet ConvertData(COpenXmlExcelSheet openXmlData)
|
||||
{
|
||||
CExcelSheet excelSheetData = new CExcelSheet();
|
||||
|
||||
//保存每列宽度。
|
||||
foreach (double width in openXmlData.WidthList)
|
||||
{
|
||||
excelSheetData.WidthList.Add(width);
|
||||
}
|
||||
|
||||
//保存每行高度。
|
||||
foreach (KeyValuePair<int, double> kvp in openXmlData.RowHeightList)
|
||||
{
|
||||
excelSheetData.RowHeightList.Add(kvp.Key, kvp.Value);
|
||||
}
|
||||
|
||||
CExcelCellData excellData = null;
|
||||
|
||||
//生成特定样式数据,并生成shared strings列表,合并单元格列表。
|
||||
int orderIndex = 0;
|
||||
foreach (List<IOpenXmlExcelStyleAndData> rowData in openXmlData.DataMatrix)
|
||||
{
|
||||
List<CExcelCellData> excelRowData = new List<CExcelCellData>();
|
||||
foreach (IOpenXmlExcelStyleAndData cellData in rowData)
|
||||
{
|
||||
excellData = new CExcelCellData();
|
||||
excelRowData.Add(excellData);
|
||||
|
||||
excellData.ApplyNumberFormat = DocumentFormat.OpenXml.BooleanValue.FromBoolean(true);
|
||||
excellData.CAlignment = cellData.CAlignment;
|
||||
excellData.CBorder = cellData.CBorder;
|
||||
excellData.CFill = cellData.CFill;
|
||||
excellData.CFont = cellData.CFont;
|
||||
|
||||
if (cellData.FormatType == CellFormatType.CSharp)
|
||||
{
|
||||
bool b = false;
|
||||
if (cellData.FormatCode != null && cellData.FormatCode.Contains("{0:MMM-yyyy}"))
|
||||
{
|
||||
b = true;
|
||||
}
|
||||
excellData.FormatCode = ConvertFormat.ConvertFormatFromCSharpToExcel(cellData.FormatCode, cellData.DataType);
|
||||
if (cellData.DataType == CellDataType.String || cellData.DataType == CellDataType.Integer)
|
||||
{
|
||||
if (b)
|
||||
{
|
||||
if (cellData.Value != null && cellData.Value.ToString().Length != 6)
|
||||
{
|
||||
excellData.FormatCode = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrEmpty(excellData.FormatCode))
|
||||
{
|
||||
excellData.Value = orderIndex;
|
||||
orderIndex++;
|
||||
excelSheetData.SharedStrings.Add(cellData.Value == null ? "" : cellData.Value.ToString());
|
||||
excellData.DataType = CellValues.SharedString;
|
||||
excellData.FormatCode = "";
|
||||
excellData.NumberFormatId = 49U;
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (cellData.DataType)
|
||||
{
|
||||
case CellDataType.Bool:
|
||||
try
|
||||
{
|
||||
|
||||
int v = 0;// Convert.ToInt16(cellData.Value);
|
||||
if (cellData.Value == null || cellData.Value.ToString() == "0" ||
|
||||
string.Equals(cellData.Value.ToString(), "false", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
v = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
v = 1;
|
||||
}
|
||||
|
||||
excellData.Value = v;
|
||||
excellData.DataType = CellValues.Number;
|
||||
}
|
||||
catch { }
|
||||
break;
|
||||
case CellDataType.Date:
|
||||
try
|
||||
{
|
||||
excellData.Value = Convert.ToDateTime(cellData.Value).ToOADate();
|
||||
excellData.DataType = CellValues.Number;
|
||||
}
|
||||
catch { }
|
||||
break;
|
||||
case CellDataType.Float:
|
||||
case CellDataType.Integer:
|
||||
excellData.Value = cellData.Value;
|
||||
excellData.DataType = CellValues.Number;
|
||||
break;
|
||||
default:
|
||||
//excellData.Value = orderIndex;
|
||||
//orderIndex++;
|
||||
//excelSheetData.SharedStrings.Add(cellData.Value == null ? "" : cellData.Value.ToString());
|
||||
//excellData.DataType = CellValues.SharedString;
|
||||
excellData.Value = (cellData.Value == null ? "" : cellData.Value.ToString());
|
||||
excellData.DataType = CellValues.String;
|
||||
excellData.FormatCode = "";
|
||||
excellData.NumberFormatId = 49U;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#region 合并单元格还没处理好。
|
||||
if (!string.IsNullOrEmpty(cellData.MergedCellsPosition))
|
||||
{
|
||||
excelSheetData.MergeCellReferenceList.Add(cellData.MergedCellsPosition);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
excelSheetData.DataMatrix.Add(excelRowData);
|
||||
}
|
||||
|
||||
return excelSheetData;
|
||||
}
|
||||
|
||||
// Adds child parts and generates content of the specified part.
|
||||
private void CreateParts(SpreadsheetDocument document, CExcelSheet excelSheetData)
|
||||
{
|
||||
WorkbookPart workbookPart = document.AddWorkbookPart();
|
||||
GenerateWorkbookPart1Content(workbookPart);
|
||||
|
||||
WorkbookStylesPart workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>("rId3");
|
||||
GenerateWorkbookStylesPart1Content(workbookStylesPart);
|
||||
|
||||
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
|
||||
GenerateWorksheetPart1Content(worksheetPart);
|
||||
|
||||
#region columns
|
||||
Columns columns = GenerateColumns(excelSheetData.WidthList);
|
||||
worksheetPart.Worksheet.Append(columns);
|
||||
#endregion
|
||||
|
||||
#region sheet data
|
||||
SheetData sheetData = GenerateSheetData(workbookStylesPart.Stylesheet, excelSheetData);
|
||||
worksheetPart.Worksheet.Append(sheetData);
|
||||
#endregion
|
||||
|
||||
#region sheet merge cells
|
||||
if (excelSheetData.MergeCellReferenceList.Count > 0)
|
||||
{
|
||||
MergeCells mergeCells = GenerateMergeCell(excelSheetData.MergeCellReferenceList);
|
||||
worksheetPart.Worksheet.Append(mergeCells);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region sheet shared strings
|
||||
if (excelSheetData.SharedStrings.Count > 0)
|
||||
{
|
||||
SharedStringTablePart sharedStringTablePart = workbookPart.AddNewPart<SharedStringTablePart>("rId4");
|
||||
GenerateSharedStringTablePart1Content(sharedStringTablePart, excelSheetData.SharedStrings);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
// Generates content of workbookPart1.
|
||||
private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
|
||||
{
|
||||
Workbook workbook1 = new Workbook();
|
||||
workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
|
||||
FileVersion fileVersion1 = new FileVersion() { ApplicationName = "xl", LastEdited = "4", LowestEdited = "4", BuildVersion = "4505" };
|
||||
WorkbookProperties workbookProperties1 = new WorkbookProperties() { DefaultThemeVersion = (UInt32Value)124226U };
|
||||
|
||||
BookViews bookViews1 = new BookViews();
|
||||
WorkbookView workbookView1 = new WorkbookView() { XWindow = 120, YWindow = 120, WindowWidth = (UInt32Value)21495U, WindowHeight = (UInt32Value)9570U };
|
||||
|
||||
bookViews1.Append(workbookView1);
|
||||
|
||||
Sheets sheets1 = new Sheets();
|
||||
Sheet sheet1 = new Sheet() { Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" };
|
||||
|
||||
sheets1.Append(sheet1);
|
||||
CalculationProperties calculationProperties1 = new CalculationProperties() { CalculationId = (UInt32Value)125725U };
|
||||
FileRecoveryProperties fileRecoveryProperties1 = new FileRecoveryProperties() { RepairLoad = true };
|
||||
|
||||
workbook1.Append(fileVersion1);
|
||||
workbook1.Append(workbookProperties1);
|
||||
workbook1.Append(bookViews1);
|
||||
workbook1.Append(sheets1);
|
||||
workbook1.Append(calculationProperties1);
|
||||
workbook1.Append(fileRecoveryProperties1);
|
||||
|
||||
workbookPart1.Workbook = workbook1;
|
||||
}
|
||||
|
||||
// Generates content of worksheetPart1.
|
||||
private void GenerateWorksheetPart1Content(WorksheetPart worksheetPart1)
|
||||
{
|
||||
Worksheet worksheet1 = new Worksheet();
|
||||
worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
|
||||
|
||||
#region sheet dimension
|
||||
//SheetDimension sheetDimension1 = new SheetDimension();// { Reference = "A1:H3" };
|
||||
//worksheet1.Append(sheetDimension1);
|
||||
#endregion
|
||||
|
||||
#region sheet views
|
||||
SheetViews sheetViews1 = new SheetViews();
|
||||
|
||||
SheetView sheetView1 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };
|
||||
Selection selection1 = new Selection() { ActiveCell = "A1", SequenceOfReferences = new ListValue<StringValue>() { InnerText = "A1" } };
|
||||
|
||||
sheetView1.Append(selection1);
|
||||
sheetViews1.Append(sheetView1);
|
||||
worksheet1.Append(sheetViews1);
|
||||
#endregion
|
||||
|
||||
#region sheet format properties
|
||||
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties() { DefaultRowHeight = 18D, CustomHeight = true };
|
||||
worksheet1.Append(sheetFormatProperties1);
|
||||
#endregion
|
||||
|
||||
#region columns 外部加入。
|
||||
//Columns columns = GenerateColumns(widthList);
|
||||
//worksheet1.Append(columns);
|
||||
#endregion
|
||||
|
||||
#region sheet data 外部加入。
|
||||
//SheetData sheetData = GenerateSheetData();
|
||||
//worksheet1.Append(sheetData);
|
||||
#endregion
|
||||
|
||||
#region merge cells
|
||||
#endregion
|
||||
|
||||
//PhoneticProperties phoneticProperties1 = new PhoneticProperties() { FontId = (UInt32Value)1U, Type = PhoneticValues.NoConversion };
|
||||
//PageMargins pageMargins1 = new PageMargins() { Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
|
||||
//PageSetup pageSetup1 = new PageSetup() { PaperSize = (UInt32Value)9U, Orientation = OrientationValues.Portrait, HorizontalDpi = (UInt32Value)200U, VerticalDpi = (UInt32Value)200U };
|
||||
|
||||
//worksheet1.Append(phoneticProperties1);
|
||||
//worksheet1.Append(pageMargins1);
|
||||
//worksheet1.Append(pageSetup1);
|
||||
|
||||
worksheetPart1.Worksheet = worksheet1;
|
||||
}
|
||||
|
||||
private Columns GenerateColumns(List<DoubleValue> columnProperties)
|
||||
{
|
||||
Columns columns = new Columns();
|
||||
Column column = null;
|
||||
UInt32Value col = 0;
|
||||
double gain = 127.0 / 750.0;
|
||||
foreach (DoubleValue dv in columnProperties)
|
||||
{
|
||||
col++;
|
||||
column = new Column() { Min = col, Max = col, Width = dv * gain, CustomWidth = true, BestFit = true };
|
||||
columns.Append(column);
|
||||
}
|
||||
|
||||
return columns;
|
||||
}
|
||||
|
||||
private Row GenerateRow(int rowIndex, List<Cell> cellsInRow, int styleIndex)
|
||||
{
|
||||
if (rowIndex < 0) return null;
|
||||
|
||||
Row row = new Row() { RowIndex = (UInt32)rowIndex };
|
||||
|
||||
if (styleIndex >= 0)
|
||||
{
|
||||
row.StyleIndex = (UInt32)styleIndex;
|
||||
}
|
||||
|
||||
if (cellsInRow.Count > 0)
|
||||
{
|
||||
row.Spans = new ListValue<StringValue>() { InnerText = "1:" + cellsInRow.Count };
|
||||
}
|
||||
|
||||
foreach (Cell cell in cellsInRow)
|
||||
{
|
||||
row.Append(cell);
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
private Cell GenerateCell(Stylesheet styleSheet, CExcelCellData cellData)
|
||||
{
|
||||
Cell cell = new Cell();
|
||||
CellValue cellValue = new CellValue();
|
||||
if (styleSheet == null)
|
||||
{
|
||||
cell.DataType = CellValues.String;
|
||||
cellValue.Text = cellData.Value == null ? "" : cellData.Value.ToString();
|
||||
cell.Append(cellValue);
|
||||
return cell;
|
||||
}
|
||||
|
||||
UInt32Value fontId = CreateFonts(styleSheet, cellData.CFont);
|
||||
UInt32Value fillId = CreateFills(styleSheet, cellData.CFill);
|
||||
UInt32Value borderId = CreateBorders(styleSheet, cellData.CBorder);
|
||||
|
||||
cell.StyleIndex = CreateCellFormat(styleSheet, fontId, fillId, borderId, cellData);
|
||||
|
||||
if (cellData.DataType != null && cellData.DataType.HasValue)
|
||||
{
|
||||
cell.DataType = cellData.DataType;
|
||||
}
|
||||
|
||||
cellValue.Text = cellData.Value == null ? "" : cellData.Value.ToString();
|
||||
cell.Append(cellValue);
|
||||
|
||||
return cell;
|
||||
}
|
||||
|
||||
private string GetFontsHashString(CellFont cellFont)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (cellFont != null)
|
||||
{
|
||||
sb.AppendLine(string.IsNullOrEmpty(cellFont.FontName) ? "" : cellFont.FontName);
|
||||
if (cellFont.FontSize != null && cellFont.FontSize.HasValue)
|
||||
{
|
||||
sb.AppendLine(cellFont.FontSize.Value.ToString());
|
||||
}
|
||||
if (cellFont.ForeColor != null)
|
||||
{
|
||||
sb.AppendLine(cellFont.ForeColor.ToArgb().ToString());
|
||||
}
|
||||
if (cellFont.IsBold != null && cellFont.IsBold.HasValue)
|
||||
{
|
||||
sb.AppendLine(cellFont.IsBold.Value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
string result = GetHashString(sb.ToString());
|
||||
return result;
|
||||
}
|
||||
|
||||
private string GetFillHashString(CellFill fill)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (fill != null)
|
||||
{
|
||||
if (fill.FillColor != null)
|
||||
{
|
||||
sb.AppendLine(fill.FillColor.ToArgb().ToString());
|
||||
}
|
||||
}
|
||||
|
||||
string result = GetHashString(sb.ToString());
|
||||
return result;
|
||||
}
|
||||
|
||||
private string GetBorderHashString(CellBorder border)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (border != null)
|
||||
{
|
||||
if (border.LeftBorder != null)
|
||||
sb.AppendLine("left");
|
||||
if (border.RightBorder != null)
|
||||
sb.AppendLine("right");
|
||||
if (border.TopBorder != null)
|
||||
sb.AppendLine("top");
|
||||
if (border.BottomBorder != null)
|
||||
sb.AppendLine("bottom");
|
||||
if (border.DialogalBorder != null)
|
||||
sb.AppendLine("dialogal");
|
||||
}
|
||||
|
||||
string result = GetHashString(sb.ToString());
|
||||
return result;
|
||||
}
|
||||
|
||||
private string GetFormatHashString(CellFormat cellFormat, string formateCode)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (cellFormat != null)
|
||||
{
|
||||
if (cellFormat.FontId != null && cellFormat.FontId.HasValue)
|
||||
sb.AppendLine(cellFormat.FontId.Value.ToString());
|
||||
if (cellFormat.ApplyFont != null && cellFormat.ApplyFont.HasValue)
|
||||
sb.AppendLine(cellFormat.ApplyFont.Value.ToString());
|
||||
|
||||
if (cellFormat.FillId != null && cellFormat.FillId.HasValue)
|
||||
sb.AppendLine(cellFormat.FillId.Value.ToString());
|
||||
if (cellFormat.ApplyFill != null && cellFormat.ApplyFill.HasValue)
|
||||
sb.AppendLine(cellFormat.ApplyFill.Value.ToString());
|
||||
|
||||
if (cellFormat.BorderId != null && cellFormat.BorderId.HasValue)
|
||||
sb.AppendLine(cellFormat.BorderId.Value.ToString());
|
||||
if (cellFormat.ApplyBorder != null && cellFormat.ApplyBorder.HasValue)
|
||||
sb.AppendLine(cellFormat.ApplyBorder.Value.ToString());
|
||||
|
||||
if (cellFormat.ApplyNumberFormat != null && cellFormat.ApplyNumberFormat.HasValue)
|
||||
sb.AppendLine(cellFormat.ApplyNumberFormat.Value.ToString());
|
||||
if (cellFormat.NumberFormatId != null && cellFormat.NumberFormatId.HasValue)
|
||||
sb.AppendLine(cellFormat.NumberFormatId.Value.ToString());
|
||||
|
||||
if (cellFormat.Alignment != null)
|
||||
{
|
||||
if (cellFormat.Alignment.Horizontal != null && cellFormat.Alignment.Horizontal.HasValue)
|
||||
sb.AppendLine(cellFormat.Alignment.Horizontal.Value.ToString());
|
||||
if (cellFormat.Alignment.Vertical != null && cellFormat.Alignment.Vertical.HasValue)
|
||||
sb.AppendLine(cellFormat.Alignment.Vertical.Value.ToString());
|
||||
if (cellFormat.ApplyAlignment != null && cellFormat.ApplyAlignment.HasValue)
|
||||
sb.AppendLine(cellFormat.ApplyAlignment.Value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
sb.AppendLine(formateCode);
|
||||
|
||||
string result = GetHashString(sb.ToString());
|
||||
return result;
|
||||
}
|
||||
|
||||
private string GetHashString(string str)
|
||||
{
|
||||
return str;
|
||||
byte[] b1 = Encoding.UTF8.GetBytes(str);
|
||||
//Cryptography.HashCode hc = new LHBIS.Security.Cryptography.HashCode(LHBIS.Security.Cryptography.HashType.htSHA256);
|
||||
//byte[] b2 = hc.ComputeHash(b1);
|
||||
//string result = LHBIS.Security.Cryptography.CommonConvert.ToHex(b2);
|
||||
//return result;
|
||||
|
||||
HashAlgorithm ha = new SHA256Managed();
|
||||
byte[] b2 = ha.ComputeHash(b1);
|
||||
string result = ToHex(b2);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string ToHex(byte[] buffer)
|
||||
{
|
||||
if (buffer == null)
|
||||
return "";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < buffer.Length; i++)
|
||||
{
|
||||
sb.Append(string.Format("{0:X2}", buffer[i]));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private SheetData GenerateSheetData(Stylesheet styleSheet, CExcelSheet data)
|
||||
{
|
||||
SheetData sheetData = new SheetData();
|
||||
Row row = null;
|
||||
Cell cell = null;
|
||||
List<Cell> cellList = null;
|
||||
int rowIndex = 0;
|
||||
|
||||
foreach (List<CExcelCellData> rowData in data.DataMatrix)
|
||||
{
|
||||
rowIndex += 1;
|
||||
cellList = new List<Cell>();
|
||||
foreach (CExcelCellData cellData in rowData)
|
||||
{
|
||||
//no style while stylesheet is null
|
||||
cell = GenerateCell(styleSheet, cellData);
|
||||
cellList.Add(cell);
|
||||
}
|
||||
//初始化行的样式为-1,表示使用缺省样式。
|
||||
row = GenerateRow(rowIndex, cellList, -1);
|
||||
if (data.RowHeightList.ContainsKey(rowIndex))
|
||||
{
|
||||
row.CustomHeight = new BooleanValue(true);
|
||||
row.Height = new DoubleValue(data.RowHeightList[rowIndex]);
|
||||
}
|
||||
|
||||
sheetData.Append(row);
|
||||
}
|
||||
return sheetData;
|
||||
}
|
||||
|
||||
private UInt32Value CreateFonts(Stylesheet styleSheet, CellFont cellFont)
|
||||
{
|
||||
if (styleSheet == null || cellFont == null) return 0U;
|
||||
|
||||
string key = GetFontsHashString(cellFont);
|
||||
UInt32Value ui32 = 0;
|
||||
if (_fontIndexCache.TryGetValue(key, out ui32))
|
||||
{
|
||||
return ui32;
|
||||
}
|
||||
|
||||
Font font = new Font();
|
||||
if (!string.IsNullOrEmpty(cellFont.FontName))
|
||||
{
|
||||
FontName name = new FontName() { Val = cellFont.FontName };
|
||||
font.Append(name);
|
||||
}
|
||||
if (cellFont.FontSize != null && cellFont.FontSize.HasValue)
|
||||
{
|
||||
FontSize size = new FontSize() { Val = cellFont.FontSize.Value };
|
||||
font.Append(size);
|
||||
}
|
||||
if (cellFont.IsBold != null && cellFont.IsBold.Value)
|
||||
{
|
||||
Bold bold = new Bold();
|
||||
font.Append(bold);
|
||||
}
|
||||
if (cellFont.ForeColor != null)
|
||||
{
|
||||
Color color = new Color();
|
||||
color.Rgb = new HexBinaryValue();
|
||||
color.Rgb.Value = System.Drawing.ColorTranslator.ToHtml(
|
||||
System.Drawing.Color.FromArgb(cellFont.ForeColor.A, cellFont.ForeColor.R, cellFont.ForeColor.G, cellFont.ForeColor.B)).Replace("#", "");
|
||||
font.Append(color);
|
||||
}
|
||||
|
||||
FontFamilyNumbering fontFamilyNumbering = new FontFamilyNumbering() { Val = 2 };
|
||||
font.Append(fontFamilyNumbering);
|
||||
FontCharSet fontCharSet = new FontCharSet() { Val = 134 };
|
||||
font.Append(fontCharSet);
|
||||
FontScheme fontScheme = new FontScheme() { Val = FontSchemeValues.Minor };
|
||||
font.Append(fontScheme);
|
||||
|
||||
if (styleSheet.Fonts == null)
|
||||
{
|
||||
styleSheet.Fonts = new Fonts();
|
||||
}
|
||||
styleSheet.Fonts.Append(font);
|
||||
UInt32Value fontID = styleSheet.Fonts.Count;
|
||||
_fontIndexCache.Add(key, fontID);
|
||||
|
||||
styleSheet.Fonts.Count++;
|
||||
return fontID;
|
||||
}
|
||||
|
||||
private UInt32Value CreateFills(Stylesheet styleSheet, CellFill cellFill)
|
||||
{
|
||||
if (styleSheet == null || cellFill == null) return 0U;
|
||||
|
||||
string key = GetFillHashString(cellFill);
|
||||
UInt32Value ui32 = 0;
|
||||
if (_fillIndexCache.TryGetValue(key, out ui32))
|
||||
{
|
||||
return ui32;
|
||||
}
|
||||
|
||||
PatternFill patternFill = new PatternFill();
|
||||
if (cellFill != null)
|
||||
{
|
||||
patternFill.Append(new ForegroundColor()
|
||||
{
|
||||
Rgb = new HexBinaryValue()
|
||||
{
|
||||
Value = System.Drawing.ColorTranslator.ToHtml(
|
||||
System.Drawing.Color.FromArgb(cellFill.FillColor.A, cellFill.FillColor.R, cellFill.FillColor.G, cellFill.FillColor.B)).Replace("#", "")
|
||||
}
|
||||
});
|
||||
patternFill.PatternType = PatternValues.Solid;
|
||||
}
|
||||
else
|
||||
{
|
||||
patternFill.PatternType = PatternValues.None;
|
||||
}
|
||||
if (styleSheet.Fills == null)
|
||||
{
|
||||
styleSheet.Fills = new Fills();
|
||||
}
|
||||
|
||||
styleSheet.Fills.Append(new Fill(patternFill));
|
||||
UInt32Value fillId = styleSheet.Fills.Count;
|
||||
_fillIndexCache.Add(key, fillId);
|
||||
styleSheet.Fills.Count++;
|
||||
return fillId;
|
||||
}
|
||||
|
||||
private UInt32Value CreateBorders(Stylesheet styleSheet, CellBorder cellBorder)
|
||||
{
|
||||
if (styleSheet == null || cellBorder == null) return 0U;
|
||||
|
||||
string key = GetBorderHashString(cellBorder);
|
||||
UInt32Value ui32 = 0;
|
||||
if (_borderIndexCache.TryGetValue(key, out ui32))
|
||||
{
|
||||
return ui32;
|
||||
}
|
||||
|
||||
Border border = new Border();
|
||||
if (cellBorder == null) return 0;
|
||||
if (cellBorder.LeftBorder != null)
|
||||
border.Append(cellBorder.LeftBorder);
|
||||
if (cellBorder.RightBorder != null)
|
||||
border.Append(cellBorder.RightBorder);
|
||||
if (cellBorder.TopBorder != null)
|
||||
border.Append(cellBorder.TopBorder);
|
||||
if (cellBorder.BottomBorder != null)
|
||||
border.Append(cellBorder.BottomBorder);
|
||||
if (cellBorder.DialogalBorder != null)
|
||||
border.Append(cellBorder.DialogalBorder);
|
||||
|
||||
if (styleSheet.Borders == null)
|
||||
{
|
||||
styleSheet.Borders = new Borders();
|
||||
}
|
||||
styleSheet.Borders.Append(border);
|
||||
UInt32Value borderId = styleSheet.Borders.Count;
|
||||
_borderIndexCache.Add(key, borderId);
|
||||
styleSheet.Borders.Count++;
|
||||
return borderId;
|
||||
}
|
||||
|
||||
private UInt32Value CreateCellFormat(Stylesheet styleSheet, UInt32Value fontIndex, UInt32Value fillIndex,
|
||||
UInt32Value borderIndex, CExcelCellData cellData)
|
||||
{
|
||||
if (styleSheet == null) return 0U;
|
||||
|
||||
CellFormat cellFormat = new CellFormat();
|
||||
if (fontIndex == null) fontIndex = 0;
|
||||
cellFormat.FontId = fontIndex;
|
||||
cellFormat.ApplyFont = BooleanValue.FromBoolean(true);
|
||||
|
||||
if (fillIndex == null) fillIndex = 0;
|
||||
cellFormat.FillId = fillIndex;
|
||||
cellFormat.ApplyFill = BooleanValue.FromBoolean(true);
|
||||
|
||||
if (borderIndex == null) borderIndex = 0;
|
||||
cellFormat.BorderId = borderIndex;
|
||||
cellFormat.ApplyBorder = BooleanValue.FromBoolean(true);
|
||||
|
||||
cellFormat.ApplyNumberFormat = cellData.ApplyNumberFormat;
|
||||
cellFormat.NumberFormatId = cellData.NumberFormatId;
|
||||
|
||||
if (cellData.CAlignment != null)
|
||||
{
|
||||
cellFormat.Append(cellData.CAlignment.Align);
|
||||
cellFormat.ApplyAlignment = BooleanValue.FromBoolean(true);
|
||||
}
|
||||
|
||||
string key = GetFormatHashString(cellFormat, cellData.FormatCode);
|
||||
UInt32Value ui32 = 0;
|
||||
if (_formatIndexCache.TryGetValue(key, out ui32))
|
||||
{
|
||||
return ui32;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(cellData.FormatCode) && cellData.FormatCode.HasValue)
|
||||
{
|
||||
cellFormat.NumberFormatId = CreateFormatId(cellData.FormatCode, styleSheet.NumberingFormats);
|
||||
}
|
||||
|
||||
styleSheet.CellFormats.Append(cellFormat);
|
||||
UInt32Value cellFormatId = styleSheet.CellFormats.Count;
|
||||
_formatIndexCache.Add(key, cellFormatId);
|
||||
styleSheet.CellFormats.Count++;
|
||||
return cellFormatId;
|
||||
}
|
||||
|
||||
private UInt32Value CreateFormatId(string formatCode, NumberingFormats numberingFormats)
|
||||
{
|
||||
NumberingFormat nf = numberingFormats.AppendChild(new NumberingFormat());
|
||||
numberingFormats.Count++;
|
||||
nf.FormatCode = formatCode;
|
||||
nf.NumberFormatId = GetMaxFormatId(numberingFormats);
|
||||
if (nf.NumberFormatId == 0)
|
||||
{
|
||||
nf.NumberFormatId = 176U;
|
||||
}
|
||||
else
|
||||
{
|
||||
nf.NumberFormatId += 1;
|
||||
}
|
||||
return nf.NumberFormatId;
|
||||
}
|
||||
|
||||
private UInt32Value GetMaxFormatId(NumberingFormats numberingFormats)
|
||||
{
|
||||
UInt32Value maxFormatId = 0U;
|
||||
foreach (NumberingFormat nf in numberingFormats.ChildElements)
|
||||
{
|
||||
if (nf.NumberFormatId != null && nf.NumberFormatId.HasValue && nf.NumberFormatId > maxFormatId)
|
||||
maxFormatId = nf.NumberFormatId;
|
||||
}
|
||||
return maxFormatId;
|
||||
}
|
||||
|
||||
// Generates content of workbookStylesPart1.
|
||||
private void GenerateWorkbookStylesPart1Content(WorkbookStylesPart workbookStylesPart1)
|
||||
{
|
||||
Stylesheet stylesheet = new Stylesheet();
|
||||
|
||||
#region default fonts
|
||||
Font font = new Font();
|
||||
FontSize fontSize = new FontSize() { Val = 11D };
|
||||
Color color = new Color() { Theme = (UInt32Value)1U };
|
||||
FontName fontName = new FontName() { Val = "宋体" };
|
||||
FontFamilyNumbering fontFamilyNumbering = new FontFamilyNumbering() { Val = 2 };
|
||||
FontCharSet fontCharSet = new FontCharSet() { Val = 134 };
|
||||
FontScheme fontScheme = new FontScheme() { Val = FontSchemeValues.Minor };
|
||||
|
||||
font.Append(fontSize);
|
||||
font.Append(color);
|
||||
font.Append(fontName);
|
||||
font.Append(fontFamilyNumbering);
|
||||
font.Append(fontCharSet);
|
||||
font.Append(fontScheme);
|
||||
|
||||
if (stylesheet.Fonts == null) stylesheet.Fonts = new Fonts() { Count = 2 };
|
||||
stylesheet.Fonts.Append(font);
|
||||
|
||||
Font font2 = new Font();
|
||||
FontSize fontSize2 = new FontSize() { Val = 9D };
|
||||
FontName fontName2 = new FontName() { Val = "宋体" };
|
||||
FontFamilyNumbering fontFamilyNumbering2 = new FontFamilyNumbering() { Val = 2 };
|
||||
FontCharSet fontCharSet2 = new FontCharSet() { Val = 134 };
|
||||
FontScheme fontScheme2 = new FontScheme() { Val = FontSchemeValues.Minor };
|
||||
|
||||
font2.Append(fontSize2);
|
||||
font2.Append(fontName2);
|
||||
font2.Append(fontFamilyNumbering2);
|
||||
font2.Append(fontCharSet2);
|
||||
font2.Append(fontScheme2);
|
||||
stylesheet.Fonts.Append(font2);
|
||||
#endregion
|
||||
|
||||
#region default fills
|
||||
Fill fill = new Fill();
|
||||
PatternFill patternFill = new PatternFill() { PatternType = PatternValues.None };
|
||||
|
||||
fill.Append(patternFill);
|
||||
|
||||
if (stylesheet.Fills == null) stylesheet.Fills = new Fills() { Count = 2 };
|
||||
stylesheet.Fills.Append(fill);
|
||||
|
||||
Fill fill2 = new Fill();
|
||||
PatternFill patternFill2 = new PatternFill() { PatternType = PatternValues.Gray125 };
|
||||
|
||||
fill2.Append(patternFill2);
|
||||
stylesheet.Fills.Append(fill2);
|
||||
#endregion
|
||||
|
||||
#region default border
|
||||
Border border = new Border();
|
||||
LeftBorder leftBorder = new LeftBorder();
|
||||
RightBorder rightBorder = new RightBorder();
|
||||
TopBorder topBorder = new TopBorder();
|
||||
BottomBorder bottomBorder = new BottomBorder();
|
||||
DiagonalBorder diagonalBorder = new DiagonalBorder();
|
||||
|
||||
border.Append(leftBorder);
|
||||
border.Append(rightBorder);
|
||||
border.Append(topBorder);
|
||||
border.Append(bottomBorder);
|
||||
border.Append(diagonalBorder);
|
||||
|
||||
if (stylesheet.Borders == null) stylesheet.Borders = new Borders() { Count = 1 };
|
||||
stylesheet.Borders.Append(border);
|
||||
#endregion
|
||||
|
||||
#region cell style format
|
||||
#endregion
|
||||
|
||||
#region cell numberingformats
|
||||
stylesheet.NumberingFormats = new NumberingFormats() { Count = (UInt32Value)0U };
|
||||
#endregion
|
||||
|
||||
#region cell format 初始化一个cell format,因为cellXfs的索引须从1开始。
|
||||
stylesheet.CellFormats = new CellFormats() { Count = 1U };
|
||||
CellFormat cf0 = stylesheet.CellFormats.AppendChild(new CellFormat());
|
||||
cf0.NumberFormatId = 0;
|
||||
cf0.FontId = 0;
|
||||
cf0.BorderId = 0;
|
||||
cf0.FillId = 0;
|
||||
#endregion
|
||||
|
||||
#region cell style
|
||||
#endregion
|
||||
workbookStylesPart1.Stylesheet = stylesheet;
|
||||
}
|
||||
|
||||
// Generates content of sharedStringTablePart1.
|
||||
private void GenerateSharedStringTablePart1Content(SharedStringTablePart sharedStringTablePart1, List<string> cellValues)
|
||||
{
|
||||
SharedStringTable sharedStringTable = new SharedStringTable() { Count = UInt32Value.FromUInt32((uint)cellValues.Count), UniqueCount = UInt32Value.FromUInt32((uint)cellValues.Count) };
|
||||
|
||||
SharedStringItem sharedStringItem = null;// new SharedStringItem();
|
||||
Text text = null;// new Text();
|
||||
foreach (string str in cellValues)
|
||||
{
|
||||
sharedStringItem = new SharedStringItem();
|
||||
text = new Text();
|
||||
|
||||
text.Text = str;
|
||||
sharedStringItem.Append(text);
|
||||
sharedStringTable.Append(sharedStringItem);
|
||||
}
|
||||
|
||||
sharedStringTablePart1.SharedStringTable = sharedStringTable;
|
||||
}
|
||||
|
||||
private MergeCells GenerateMergeCell(List<string> mergeCellReferenceList)
|
||||
{
|
||||
MergeCells mcells = new MergeCells() { Count = UInt32Value.FromUInt32((uint)mergeCellReferenceList.Count) };
|
||||
if (mcells == null || mergeCellReferenceList == null || mergeCellReferenceList.Count <= 0) return mcells;
|
||||
var mergeCells = mergeCellReferenceList.Select((s) =>
|
||||
{
|
||||
return new MergeCell() { Reference = s };
|
||||
});
|
||||
|
||||
foreach (var o in mergeCells)
|
||||
{
|
||||
mcells.Append(o);
|
||||
}
|
||||
return mcells;
|
||||
}
|
||||
}
|
||||
}
|
483
IronIntelContractorBusiness/ExportExcel/ExportToExcel.cs
Normal file
483
IronIntelContractorBusiness/ExportExcel/ExportToExcel.cs
Normal file
@ -0,0 +1,483 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
using System.Xml.Linq;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using DocumentFormat.OpenXml;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Data;
|
||||
|
||||
namespace IronIntel.Contractor
|
||||
{
|
||||
internal class ChartFormatedData : IOpenXmlExcelStyleAndData
|
||||
{
|
||||
public ChartFormatedData()
|
||||
{
|
||||
FormatType = CellFormatType.CSharp;
|
||||
}
|
||||
|
||||
#region IOpenXmlExcelStyleAndData Members
|
||||
|
||||
public CellAlignment CAlignment { get; set; }
|
||||
|
||||
public CellBorder CBorder { get; set; }
|
||||
|
||||
public CellFill CFill { get; set; }
|
||||
|
||||
public CellFont CFont { get; set; }
|
||||
|
||||
public CellDataType DataType { get; set; }
|
||||
|
||||
public string FormatCode { get; set; }
|
||||
|
||||
public CellFormatType FormatType { get; set; }
|
||||
|
||||
public object Value { get; set; }
|
||||
|
||||
public String MergedCellsPosition { get; set; }
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
public class ExportToExcel
|
||||
{
|
||||
/// <summary>
|
||||
/// 将DataTable的数据导出到Excel
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public byte[] CreateExcel(DataTable data, string caption, double[] columnWidths, string[] MergeTitles)
|
||||
{
|
||||
COpenXmlExcelSheet osheet = ConvertToOpenXmlObject(data, caption, columnWidths, MergeTitles);
|
||||
|
||||
MemoryStream ms = null;
|
||||
try
|
||||
{
|
||||
ms = new MemoryStream();
|
||||
ExcelXlsx xls = new ExcelXlsx();
|
||||
xls.CreatePackage(ms, osheet);
|
||||
ms.Position = 0;
|
||||
|
||||
byte[] bts = new byte[ms.Length];
|
||||
int offset = 0;
|
||||
while (offset < bts.Length)
|
||||
{
|
||||
offset += ms.Read(bts, offset, bts.Length - offset);
|
||||
}
|
||||
|
||||
return bts;
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
if (ms != null)
|
||||
ms.Close();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private object ConvertIvalidChars(object s)
|
||||
{
|
||||
if (s == null) return null;
|
||||
if (s.GetType() != typeof(string)) return s;
|
||||
const string invalidCharsMatch =
|
||||
"(?ims)[\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf" +
|
||||
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f]";
|
||||
|
||||
//取代其中無效字元, 通通換成空字串
|
||||
s = Regex.Replace(
|
||||
s.ToString(),
|
||||
invalidCharsMatch, "");
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
private COpenXmlExcelSheet ConvertToOpenXmlObject(DataTable data, string caption, double[] columnWidths, string[] MergeTitles)
|
||||
{
|
||||
try
|
||||
{
|
||||
COpenXmlExcelSheet osheet = new COpenXmlExcelSheet();
|
||||
|
||||
// 设置数据和格式。
|
||||
|
||||
//所有数据和格式存放在此结构中。
|
||||
List<List<IOpenXmlExcelStyleAndData>> dataMatrix = new List<List<IOpenXmlExcelStyleAndData>>();
|
||||
osheet.DataMatrix = dataMatrix;
|
||||
|
||||
//行数据临时对象。
|
||||
List<IOpenXmlExcelStyleAndData> rowData = null;
|
||||
//单元格数据临时对象。
|
||||
ChartFormatedData cellData = null;
|
||||
|
||||
DataRow rdr = null;
|
||||
DataColumn rdc = null;
|
||||
|
||||
#region 设置宽度。
|
||||
|
||||
foreach (var w in columnWidths)
|
||||
{
|
||||
osheet.WidthList.Add(w);
|
||||
}
|
||||
//for (int k = 0; k < dataFromClient.Columns.Count; k++)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// rdc = dataFromClient.Columns[k];
|
||||
// if (rdc.Attributes == null || !rdc.Attributes.ContainsKey("Width"))
|
||||
// {
|
||||
// osheet.WidthList.Add(100);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// osheet.WidthList.Add(Convert.ToDouble(rdc.Attributes["Width"]));
|
||||
// }
|
||||
// }
|
||||
// catch
|
||||
// {
|
||||
// }
|
||||
//}
|
||||
|
||||
#endregion
|
||||
|
||||
int rowIndex = 0;
|
||||
|
||||
#region caption
|
||||
|
||||
if (!string.IsNullOrEmpty(caption))
|
||||
{
|
||||
rowData = new List<IOpenXmlExcelStyleAndData>();
|
||||
cellData = new ChartFormatedData();
|
||||
cellData.CAlignment = new CellAlignment();
|
||||
cellData.CAlignment.Align = GetAlignment("center");
|
||||
cellData.DataType = CellDataType.String;
|
||||
cellData.FormatCode = "";
|
||||
|
||||
cellData.CFont = new CellFont();
|
||||
cellData.CFont.FontSize = 14;
|
||||
|
||||
cellData.Value = caption;
|
||||
cellData.MergedCellsPosition = "A1:" + ConvertColNumber(data.Columns.Count) + "1";
|
||||
|
||||
rowData.Add(cellData);
|
||||
rowIndex += 1;
|
||||
dataMatrix.Add(rowData);
|
||||
|
||||
//设置第一行的高度。
|
||||
osheet.RowHeightList.Add(rowIndex, 23);
|
||||
|
||||
//添加一个空行。
|
||||
rowData = new List<IOpenXmlExcelStyleAndData>();
|
||||
cellData = new ChartFormatedData();
|
||||
cellData.MergedCellsPosition = "A2:" + ConvertColNumber(data.Columns.Count) + "2";
|
||||
rowData.Add(cellData);
|
||||
rowIndex += 1;
|
||||
dataMatrix.Add(rowData);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region MergeTitles
|
||||
|
||||
if (MergeTitles != null && MergeTitles.Length % 2 == 0)
|
||||
{
|
||||
rowData = new List<IOpenXmlExcelStyleAndData>();
|
||||
|
||||
for (int q = 0; q < data.Columns.Count; q++)
|
||||
{
|
||||
cellData = new ChartFormatedData();
|
||||
cellData.CAlignment = new CellAlignment();
|
||||
cellData.CAlignment.Align = GetAlignment("center");
|
||||
cellData.DataType = CellDataType.String;
|
||||
cellData.FormatCode = "";
|
||||
|
||||
cellData.CFont = new CellFont();
|
||||
cellData.CFont.FontSize = 14;
|
||||
|
||||
rowData.Add(cellData);
|
||||
}
|
||||
|
||||
for (int i = 0; i < MergeTitles.Length; i += 2)
|
||||
{
|
||||
string[] tmp = MergeTitles[i + 1].Split('-');
|
||||
if (tmp.Length == 1) continue;
|
||||
|
||||
cellData = (ChartFormatedData)rowData[(Convert.ToInt32(tmp[0]) - 1)];
|
||||
cellData.Value = MergeTitles[i];
|
||||
cellData.MergedCellsPosition = ConvertColNumber(Convert.ToInt32(tmp[0])) + "3:" + ConvertColNumber(Convert.ToInt32(tmp[1])) + "3";
|
||||
}
|
||||
|
||||
rowIndex += 1;
|
||||
dataMatrix.Add(rowData);
|
||||
//设置第一行的高度。
|
||||
osheet.RowHeightList.Add(rowIndex, 15);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region header。
|
||||
|
||||
rowData = new List<IOpenXmlExcelStyleAndData>();
|
||||
|
||||
for (int q = 0; q < data.Columns.Count; q++)
|
||||
{
|
||||
rdc = data.Columns[q];
|
||||
cellData = new ChartFormatedData();
|
||||
|
||||
string alignment = "";
|
||||
if (rdc != null)
|
||||
{
|
||||
//if (rdc.Attributes != null && rdc.Attributes.ContainsKey("Alignment"))
|
||||
//{
|
||||
// alignment = rdc.Attributes["Alignment"];
|
||||
//}
|
||||
|
||||
cellData.CAlignment = new CellAlignment();
|
||||
cellData.CAlignment.Align = GetAlignment(alignment);
|
||||
|
||||
cellData.CFont = new CellFont();
|
||||
cellData.CFont.IsBold = true;
|
||||
|
||||
cellData.CFill = new CellFill();
|
||||
cellData.CFill.FillColor = System.Drawing.Color.Gray;
|
||||
|
||||
cellData.DataType = CellDataType.String;
|
||||
cellData.FormatCode = "";
|
||||
}
|
||||
|
||||
cellData.Value = rdc.ColumnName;
|
||||
|
||||
rowData.Add(cellData);
|
||||
}
|
||||
rowIndex += 1;
|
||||
osheet.RowHeightList.Add(rowIndex, 18);
|
||||
dataMatrix.Add(rowData);
|
||||
|
||||
#endregion
|
||||
|
||||
#region real data 。
|
||||
|
||||
for (int k = 0; k <= data.Rows.Count - 1; k++)
|
||||
{
|
||||
rdr = data.Rows[k];
|
||||
rowData = new List<IOpenXmlExcelStyleAndData>();
|
||||
|
||||
for (int q = 0; q < data.Columns.Count; q++)
|
||||
{
|
||||
rdc = data.Columns[q];
|
||||
|
||||
string format = "";
|
||||
//if (rdc != null)
|
||||
//{
|
||||
//if (rdc.Attributes != null && rdc.Attributes.ContainsKey("DataFormat"))
|
||||
//{
|
||||
// format = (rdc.Attributes["DataFormat"] == null
|
||||
// ? ""
|
||||
// : rdc.Attributes["DataFormat"].ToString());
|
||||
//}
|
||||
//}
|
||||
|
||||
cellData = new ChartFormatedData();
|
||||
|
||||
//将特殊格式值处理成字符串显示。
|
||||
if (rdr != null)
|
||||
{
|
||||
bool isProcessed = false;
|
||||
cellData.Value =
|
||||
ConvertIvalidChars(
|
||||
ProcessSpecialFormat(rdr[q], format, ref isProcessed));
|
||||
if (isProcessed) format = "";
|
||||
}
|
||||
cellData.FormatCode = ProcessFormat(format);
|
||||
cellData.DataType =
|
||||
GetDataType((cellData.Value == null ? typeof(string) : cellData.Value.GetType()));
|
||||
|
||||
string alignment = "";
|
||||
if (rdc != null)
|
||||
{
|
||||
//if (rdc.Attributes != null && rdc.Attributes.ContainsKey("Alignment"))
|
||||
//{
|
||||
// alignment = rdc.Attributes["Alignment"];
|
||||
//}
|
||||
cellData.CAlignment = new CellAlignment();
|
||||
cellData.CAlignment.Align = GetAlignment(alignment);
|
||||
}
|
||||
|
||||
//如果是合计行则以浅灰色显示。
|
||||
//if (hasTotalRow && k == dataFromClient.Rows.Count - 1)
|
||||
//{
|
||||
// cellData.CFill = new CellFill();
|
||||
// cellData.CFill.FillColor = System.Drawing.Color.LightGray;
|
||||
//}
|
||||
|
||||
//如果是合计列则以浅灰色显示。
|
||||
//if (hasTotalColumn && q == dataFromClient.Columns.Count - 1)
|
||||
//{
|
||||
// cellData.CFill = new CellFill();
|
||||
// cellData.CFill.FillColor = System.Drawing.Color.LightGray;
|
||||
//}
|
||||
|
||||
rowData.Add(cellData);
|
||||
}
|
||||
|
||||
//rowIndex += 1;
|
||||
//if (hasTotalRow && k == dataFromClient.Rows.Count - 1)
|
||||
//{
|
||||
// osheet.RowHeightList.Add(rowIndex, totalRowHeight);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// osheet.RowHeightList.Add(rowIndex, 18);
|
||||
//}
|
||||
|
||||
dataMatrix.Add(rowData);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
return osheet;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
private string ConvertColNumber(int colnum)
|
||||
{
|
||||
string zzz = "Z+";
|
||||
Regex reg = new Regex(zzz);
|
||||
string result = "";
|
||||
MatchCollection mc = null;
|
||||
for (int k = 0; k < colnum; k++)
|
||||
{
|
||||
mc = reg.Matches(result);
|
||||
if (mc.Count > 0)
|
||||
{
|
||||
//是zzz格式。
|
||||
string first = result.Substring(0, mc[0].Index);
|
||||
if (string.IsNullOrEmpty(first))
|
||||
{
|
||||
result = result.Replace("Z", "A") + "A";
|
||||
}
|
||||
else
|
||||
{
|
||||
char c = first[first.Length - 1];
|
||||
c = Convert.ToChar(c + 1);
|
||||
result = c.ToString() + result.Substring(mc[0].Index).Replace("Z", "A");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(result))
|
||||
{
|
||||
result = "A";
|
||||
}
|
||||
else
|
||||
{
|
||||
char c = result[result.Length - 1];
|
||||
c = Convert.ToChar(c + 1);
|
||||
result = result.Substring(0, result.Length - 1) + c.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Alignment GetAlignment(string align)
|
||||
{
|
||||
Alignment horizon = new Alignment() { Horizontal = HorizontalAlignmentValues.Left, WrapText = true };
|
||||
|
||||
if (string.Equals(align, "center", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
horizon = new Alignment() { Horizontal = HorizontalAlignmentValues.Center, WrapText = true };
|
||||
}
|
||||
else if (string.Equals(align, "right", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
horizon = new Alignment() { Horizontal = HorizontalAlignmentValues.Right, WrapText = true };
|
||||
}
|
||||
|
||||
return horizon;
|
||||
}
|
||||
|
||||
private CellDataType GetDataType(Type typ)
|
||||
{
|
||||
CellDataType result = CellDataType.String;
|
||||
|
||||
switch (Type.GetTypeCode(typ))
|
||||
{
|
||||
case TypeCode.Int16:
|
||||
case TypeCode.Int32:
|
||||
case TypeCode.Int64:
|
||||
case TypeCode.UInt16:
|
||||
case TypeCode.UInt32:
|
||||
case TypeCode.UInt64:
|
||||
result = CellDataType.Integer;
|
||||
break;
|
||||
case TypeCode.Decimal:
|
||||
case TypeCode.Double:
|
||||
case TypeCode.Single:
|
||||
result = CellDataType.Float;
|
||||
break;
|
||||
case TypeCode.DateTime:
|
||||
result = CellDataType.Date;
|
||||
break;
|
||||
case TypeCode.Boolean:
|
||||
result = CellDataType.Bool;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private object ProcessSpecialFormat(object val, string format, ref bool isProcessed)
|
||||
{
|
||||
object result = val;
|
||||
isProcessed = false;
|
||||
if (val == null || string.IsNullOrEmpty(format.Trim())) return result;
|
||||
|
||||
CellDataType typ = GetDataType(result.GetType());
|
||||
|
||||
//第一个特殊格式:如果值是6位字符串,格式是"MMM-yyyy",则按日期处理。
|
||||
if (typ == CellDataType.String && string.Equals(format.Replace(" ", ""), "{0:MMM-yyyy}"))
|
||||
{
|
||||
string str = result.ToString();
|
||||
if (str.Length == 6)
|
||||
{
|
||||
try
|
||||
{
|
||||
result = new DateTime(Convert.ToInt32(str.Substring(0, 4)), Convert.ToInt32(str.Substring(4)), 1);
|
||||
result = string.Format(format, result);
|
||||
isProcessed = true;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// 处理Format格式,使一些特殊符号(如:*、@)可以直接在Excel中看到,而不是解释成Excel中对这些符号的定义
|
||||
/// </summary>
|
||||
/// <param name="format">格式字符串</param>
|
||||
/// <returns></returns>
|
||||
private string ProcessFormat(string format)
|
||||
{
|
||||
string resultFormat = format;
|
||||
if (string.IsNullOrEmpty(resultFormat)) return resultFormat;
|
||||
if (format.IndexOf("*") >= 0)
|
||||
{
|
||||
resultFormat = resultFormat.Replace("*", "\"*\"");
|
||||
}
|
||||
if (format.IndexOf("@") >= 0)
|
||||
{
|
||||
resultFormat = resultFormat.Replace("@", "\"@\"");
|
||||
}
|
||||
return resultFormat;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,130 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
|
||||
namespace IronIntel.Contractor
|
||||
{
|
||||
/// <summary>
|
||||
/// 单元格数据类型
|
||||
/// </summary>
|
||||
public enum CellDataType
|
||||
{
|
||||
String, Bool, Date, Guid, Float, Integer
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单元格格式类型
|
||||
/// </summary>
|
||||
public enum CellFormatType
|
||||
{
|
||||
CSharp, Excel
|
||||
}
|
||||
|
||||
#region 单元格边界样式 Cell Border
|
||||
public enum EBorder
|
||||
{
|
||||
None, Single, Double
|
||||
}
|
||||
public class CellBorder
|
||||
{
|
||||
public LeftBorder LeftBorder { get; set; }
|
||||
public RightBorder RightBorder { get; set; }
|
||||
public TopBorder TopBorder { get; set; }
|
||||
public BottomBorder BottomBorder { get; set; }
|
||||
public DiagonalBorder DialogalBorder { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 单元格对齐方式
|
||||
/// </summary>
|
||||
#region cell alignment
|
||||
public class CellAlignment
|
||||
{
|
||||
public Alignment Align { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 单元格填充颜色
|
||||
/// </summary>
|
||||
#region cell fill
|
||||
public class CellFill
|
||||
{
|
||||
public System.Drawing.Color FillColor { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 单元格字体
|
||||
/// </summary>
|
||||
#region cell font
|
||||
public class CellFont
|
||||
{
|
||||
public string FontName { get; set; }
|
||||
public DoubleValue FontSize { get; set; }
|
||||
public BooleanValue IsBold { get; set; }
|
||||
public System.Drawing.Color ForeColor { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 单元格样式和数据。
|
||||
/// </summary>
|
||||
public interface IOpenXmlExcelStyleAndData
|
||||
{
|
||||
//单元格数据值
|
||||
object Value { get; set; }
|
||||
|
||||
//单元格数据类型
|
||||
CellDataType DataType { get; set; }
|
||||
|
||||
//单元格数据颜色
|
||||
CellFont CFont { get; set; }
|
||||
|
||||
//单元格数据格式
|
||||
CellFormatType FormatType { get; set; }
|
||||
String FormatCode { get; set; }
|
||||
|
||||
//单元格边界样式
|
||||
CellBorder CBorder { get; set; }
|
||||
|
||||
//单元格对齐方式
|
||||
CellAlignment CAlignment { get; set; }
|
||||
|
||||
//填充颜色
|
||||
CellFill CFill { get; set; }
|
||||
|
||||
//合并单元格需要合并的
|
||||
String MergedCellsPosition { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// excel sheet 数据和样式集合。
|
||||
/// </summary>
|
||||
public class COpenXmlExcelSheet
|
||||
{
|
||||
public List<List<IOpenXmlExcelStyleAndData>> DataMatrix
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
private List<double> _WidthList = new List<double>();
|
||||
public List<double> WidthList
|
||||
{
|
||||
get { return _WidthList; }
|
||||
}
|
||||
|
||||
Dictionary<int, double> _RowHeightList = new Dictionary<int, double>();
|
||||
public Dictionary<int, double> RowHeightList
|
||||
{
|
||||
get { return _RowHeightList; }
|
||||
}
|
||||
}
|
||||
}
|
73
IronIntelContractorBusiness/ExportExcel/XlsxObj.cs
Normal file
73
IronIntelContractorBusiness/ExportExcel/XlsxObj.cs
Normal file
@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using Ap = DocumentFormat.OpenXml.ExtendedProperties;
|
||||
using Vt = DocumentFormat.OpenXml.VariantTypes;
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using A = DocumentFormat.OpenXml.Drawing;
|
||||
|
||||
namespace IronIntel.Contractor
|
||||
{
|
||||
internal class CExcelCellData
|
||||
{
|
||||
//单元格数据值
|
||||
public object Value { get; set; }
|
||||
|
||||
//单元格数据类型
|
||||
public EnumValue<CellValues> DataType { get; set; }
|
||||
|
||||
//单元格数据颜色
|
||||
public CellFont CFont { get; set; }
|
||||
|
||||
//单元格数据格式
|
||||
public UInt32Value NumberFormatId { get; set; }
|
||||
public BooleanValue ApplyNumberFormat { get; set; }
|
||||
public StringValue FormatCode { get; set; }
|
||||
|
||||
//单元格边界样式
|
||||
public CellBorder CBorder { get; set; }
|
||||
|
||||
//单元格对齐方式
|
||||
public CellAlignment CAlignment { get; set; }
|
||||
|
||||
//填充颜色
|
||||
public CellFill CFill { get; set; }
|
||||
}
|
||||
|
||||
internal class CExcelSheet
|
||||
{
|
||||
private List<List<CExcelCellData>> _DataMatrix = new List<List<CExcelCellData>>();
|
||||
public List<List<CExcelCellData>> DataMatrix
|
||||
{
|
||||
get { return _DataMatrix; }
|
||||
}
|
||||
|
||||
private List<string> _SharedStrings = new List<string>();
|
||||
public List<string> SharedStrings
|
||||
{
|
||||
get { return _SharedStrings; }
|
||||
}
|
||||
|
||||
List<string> _MergeCellReferenceList = new List<string>();
|
||||
public List<string> MergeCellReferenceList
|
||||
{
|
||||
get { return _MergeCellReferenceList; }
|
||||
}
|
||||
|
||||
List<DoubleValue> _WidthList = new List<DoubleValue>();
|
||||
public List<DoubleValue> WidthList
|
||||
{
|
||||
get { return _WidthList; }
|
||||
}
|
||||
|
||||
Dictionary<int, DoubleValue> _RowHeightList = new Dictionary<int, DoubleValue>();
|
||||
public Dictionary<int, DoubleValue> RowHeightList
|
||||
{
|
||||
get { return _RowHeightList; }
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user