[]
If you want to get or set column width by pixels, the result may appear different in DsExcel and Excel as both of them store column width by characters. To overcome this issue, DsExcel supports measuring digital width in order to calculate the accurate pixel value of a single digit.
DsExcel provides IGraphicsInfo interface in its API which can be implemented to know the accurate pixel value of a single digit. The getDigitWidth method in IGraphicsInfo interface measures the text (or characters) based on different font attributes like font family, font size, font style etc. DsExcel API also supports GUI frameworks, such as WPF and Windows Forms.
Refer to the following example code which calculates the pixel value and exports the column width correctly in Excel.
public class FakeGraphicsInfo implements IGraphicsInfo {
public double Width;
public int GetDigitWidthCount;
public double setWidth(double i) {
return i;
}
public double getWidth(double i) {
return i;
}
@Override
public double getDigitWidth(TextFormatInfo textFormat) {
GetDigitWidthCount++;
return 1;
}
}
// Create a new workbook
Workbook workbook = new Workbook();
// Create theme
Theme theme = new Theme("custom");
theme.getThemeFontScheme().getMajor().get(FontLanguageIndex.Latin).setName("YouthTouchDemoRegular");
theme.getThemeFontScheme().getMinor().get(FontLanguageIndex.Latin).setName("YouthTouchDemoRegular");
workbook.setTheme(theme);
// Get worksheet
IWorksheet sheet = workbook.getWorksheets().get(0);
FakeGraphicsInfo fakeGraphicsInfo = new FakeGraphicsInfo();
fakeGraphicsInfo.setWidth(8);
workbook.setGraphicsInfo(fakeGraphicsInfo);
sheet.setStandardWidthInPixel(20);
sheet.getColumns().get(0).setColumnWidthInPixel(20);
sheet.getRange(1, 1).setValue("abc");
// Save workbook
workbook.save("MeasureDigitalWidthAccurately.xlsx");
type=note
Note: Please note below points:
- The above sample requires WinForms application to build and run.
- The result of getDigitWidth method is environment-dependent. Sometimes, it returns different results when running on different computers.